美文网首页Android代码封装
iOS使用Flutter_Boost管理页面跳转

iOS使用Flutter_Boost管理页面跳转

作者: Alan_Bei | 来源:发表于2020-04-16 21:13 被阅读0次

上一篇文章介绍了如何集成Flutter_Boost,本篇将详细介绍flutter如何与原生进行交互。

首先给出文章demo,具体代码可作参考。

一:flutter_module项目使用FlutterBoost进行路由配置
import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'simple_page_widgets.dart';

void main() {
  run App(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    FlutterBoost.singleton.registerPageBuilders({
      'first': (pageName, params, _) => FirstRouteWidget(),
      'second': (pageName, params, _) => SecondRouteWidget(),
      'flutterPage': (pageName, params, _) {
        print("flutterPage params:$params");
        return FlutterRouteWidget(params:params);
      },
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter example',
        builder: FlutterBoost.init(postPush: _onRoutePushed),
        home: Container());
  }

  void _onRoutePushed(
      String pageName, String uniqueId, Map params, Route route, Future _) {
  }
}

这里首先在Widget builder中初始化了FlutterBoost,然后在initState方法中通过FlutterBoost为三个页面注册了路由,这里注册的路由是原生与flutter通用的,这个后面可以体现。

二:在Flutter页面路由中使用FlutterBoost跳转

总结在Flutter中有以下几种跳转方式:
1.Flutter=>Flutter(使用Flutter自己的路由)

Navigator.push(context, MaterialPageRoute(builder: (_) => FirstRouteWidget()));

以下三种跳转方式,都是通过FlutterBoost进行跳转,使用的是同一个方法,只是场景有所不同

FlutterBoost.singleton.open( String url,{Map<dynamic,dynamic> urlParams,Map<dynamic,dynamic> exts)

参数分别为:页面名称,通信传参,扩展参数。对应相应跳转方式使用如下:
2.Flutter=>Flutter(使用原生的navigationController)
例:first页面打开路由名称为second页面,传参为{"query": “aaa”},扩展参数中可以添加一些特殊数据,这里添加了{"animated": true},在原生中会解析为带动画跳转

FlutterBoost.singleton.open( "second",urlParams: {"query": "aaa"}, exts: {"animated": true})

3.Flutter=>原生(push)
例:first页面打开原生NativeViewController页面,拼接native将在原生项目中解析为跳转原生页面,拼接push表明跳转方式。

FlutterBoost.singleton.open( "native_push_NativeViewController",urlParams: {"query": "aaa"}, exts: {"animated": true})

4.Flutter=>原生(present)
同上,使用present跳转方式。

FlutterBoost.singleton.open( "native_present_NativeViewController",urlParams: {"query": "aaa"}, exts: {"animated": true})

另外,Flutter关闭或返回上级页面使用的是close方法,分为两种
1.关闭当前页面

FlutterBoost.singleton.closeCurrent(result: {}, exts: {});

2.通过id关闭指定页面

FlutterBoost.singleton.close('id', result: {}, exts: {});
三:原生项目中配置路由通信
import Foundation

//实现FLBPlatform协议方法,flutter项目和原生项目使用FlutterBoost进行的跳转都会通过该类进行处理
class PlatformRouterImp: NSObject, FLBPlatform {
    //处理打开原生页面逻辑
    func openNative(_ url: String, urlParams: [AnyHashable : Any], exts: [AnyHashable : Any], completion: @escaping (Bool) -> Void) {
        var animated = false
        if exts["animated"] != nil{
            animated = exts["animated"] as! Bool
        }
        //与flutter端约定跳转原生的url为三段式结构native_method_name
        let urlArr = url.components(separatedBy: "_")
        if urlArr.count == 3 {
            //通过类名找到相应页面
            let cls : AnyClass? = NSClassFromString("TestWithFlutter." + urlArr[2])
            //该项目中的vc都继承于BaseViewController,加了一个params用来接收Flutter传过来的参数,另有方案的话改为UIViewController即可。
            if let clsType = cls as? BaseViewController.Type {
                let targetVC = clsType.init()
                targetVC.params = urlParams
                if urlArr[1] == "push" {
                    self.navigationController().pushViewController(targetVC, animated: animated)
                    completion(true)
                } else if urlArr[1] == "present" {
                    let navVC = UINavigationController(rootViewController: targetVC)
                    self.navigationController().present(navVC, animated: animated) {
                        completion(true)
                    }
                }
            }
        }
    }
    //FlutterBoost的open方法会在这里进行处理
    func open(_ url: String, urlParams: [AnyHashable : Any], exts: [AnyHashable : Any], completion: @escaping (Bool) -> Void) {
        if url.prefix(6) == "native" {//约定前面字符为native时跳转原生页面
            openNative(url, urlParams: urlParams, exts: exts, completion: completion)
        } else {//否则打开Flutter页面
            var animated = false
            if exts["animated"] != nil{
                animated = exts["animated"] as! Bool
            }
            let vc = FLBFlutterViewContainer.init()
            vc.setName(url, params: urlParams)
            self.navigationController().pushViewController(vc, animated: animated)
            completion(true)
        }
    }
    //FlutterBoost的present方法会在这里进行处理,Flutter项目中不分present打开方式,都会走open方法
    func present(_ url: String, urlParams: [AnyHashable : Any], exts: [AnyHashable : Any], completion: @escaping (Bool) -> Void) {
        //直接present出的navVC,会导致flutter路由中uniqueid混乱,有待研究
//        var animated = false
//        if exts["animated"] != nil{
//            animated = exts["animated"] as! Bool
//        }
        let vc = FLBFlutterViewContainer.init()
        vc.setName(url, params: urlParams)
        let navVC = UINavigationController(rootViewController: vc)
        navVC.modalPresentationStyle = .fullScreen
        let delegate = UIApplication.shared.delegate as! AppDelegate
        delegate.window?.rootViewController = navVC
//        navigationController().present(navVC, animated: animated) {
//            completion(true)
//        }
    }
    //FlutterBoost的close方法会在这里进行处理
    func close(_ uid: String, result: [AnyHashable : Any], exts: [AnyHashable : Any], completion: @escaping (Bool) -> Void) {
        var animated = false;
        if exts["animated"] != nil{
            animated = exts["animated"] as! Bool
        }
        let presentedVC = self.navigationController().presentedViewController
        let vc = presentedVC as? FLBFlutterViewContainer
        if vc?.uniqueIDString() == uid {
            vc?.dismiss(animated: animated, completion: {
                completion(true)
            })
        }else{
            self.navigationController().popViewController(animated: animated)
        }
    }
    //获取应用的navigationController,用来进行跳转
    func navigationController() -> UINavigationController {
        let delegate = UIApplication.shared.delegate as! AppDelegate
        let navigationController = delegate.window?.rootViewController as! UINavigationController
        return navigationController
    }
}
四:在AppDelegate中初始化FlutterBoost
import UIKit
import Flutter

@UIApplicationMain
class AppDelegate: FlutterAppDelegate {
    
    override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        let router = PlatformRouterImp.init();
        FlutterBoostPlugin.sharedInstance().startFlutter(with: router, onStart: { (engine) in
        });
        
        self.window = UIWindow.init(frame: UIScreen.main.bounds)
        let viewController = ViewController.init()
        let navi = UINavigationController.init(rootViewController: viewController)
        self.window.rootViewController = navi
        self.window.makeKeyAndVisible()
        
        return true
    }
    
}
五:原生使用FlutterBoost进行跳转

例:原生跳转Flutter路由名为flutterPage的页面

        FlutterBoostPlugin.open("flutterPage", urlParams:["query":"aaa"], exts: ["animated":true], onPageFinished: { (_ result:Any?) in
            print(String(format:"call me when page finished, and your result is:%@", result as! CVarArg));
        }) { (f:Bool) in
            print(String(format:"page is opened"));
        }

相关文章

网友评论

    本文标题:iOS使用Flutter_Boost管理页面跳转

    本文链接:https://www.haomeiwen.com/subject/mcfjvhtx.html