美文网首页
在iOS原生项目中集成Flutter登录界面

在iOS原生项目中集成Flutter登录界面

作者: 麦子maizi | 来源:发表于2022-04-02 11:57 被阅读0次

    1、已有项目工程(iOS)集成Flutter

    (1)关闭Bitcode,cd到iOS工程最外层,在终端输入生成flutter工程

    flutter create -t module flutter_project
    

    结束后项目结构如下

    - flutter_project
    -- lib
    --- main.dart
    
    - iOS_project
    -- .xcworkspace
    

    (2)Podfile文件示例,在{}内分别填入flutter工程路径和iOS工程名称

    platform :ios, '9.0'
    use_frameworks!
    flutter_application_path = '{flutter_project路径}'
    load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
    target '{iOS项目名称}' do
    install_all_flutter_pods(flutter_application_path)
    end
    

    2、iOS项目和Flutter文件的相互调用

    (1)iOS工程AppDelegate文件

    import UIKit
    import Flutter
    import FlutterPluginRegistrant
    
    @main
    class AppDelegate: FlutterAppDelegate {
        
        let flutterMethodChannel = "flutter_channel"
        lazy var flutterEngine = FlutterEngine(name: "flutter_engine")
        
    
        override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            flutterEngine.run()
            GeneratedPluginRegistrant.register(with: self.flutterEngine)
            TYFlutterManager.register(with: self.flutterEngine.registrar(forPlugin: "TYFlutterManager")!)
            return super.application(application, didFinishLaunchingWithOptions: launchOptions)
        }
    }
    
    

    (2)iOS工程新建一个类TYFlutter声明通道,注册代理回调,通道名为flutter_channel

    import Foundation
    import Flutter
    class TYFlutterManager: NSObject, FlutterPlugin {
        static func register(with registrar: FlutterPluginRegistrar) {
            let channel = FlutterMethodChannel(name: "flutter_channel", binaryMessenger: registrar.messenger())
            let instance = TYFlutterManager()
            registrar.addMethodCallDelegate(instance, channel: channel)
        }
        
        func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
            if call.method == "flutterCalliOS" {
           
            } else {
                result(FlutterMethodNotImplemented)
            }
        }
        
    }
    

    (3)原生跳转Flutter页面

    let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
    let flutterVC     = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
    flutterVC.setInitialRoute("LoginPage")
    present(flutterVC, animated: true, completion: nil)
    

    (4)Flutter调用原生,Flutter工程新建一个.dart文件flutter 调用 原生的函数,通道名也是flutter_channel

    const platform =  const MethodChannel('flutter_channel');
    
    /// 路由
    /// 返回上一级
    Future dismissPage() async {
      var result;
      try {
        //传递给原生的方法名和参数
        result = await platform.invokeMethod('flutterCalliOS',
            {'function':'dismiss'});
        //接收原生传过来的值
        return Future.value(result);
      } on PlatformException catch(e) {
        return Future.error(e.toString());
      }
    }
    

    (5)Flutter开始调用声明的函数,比如在flutter页面点击返回

    () async{
        var futureValue = await dismissPage();
        //接收的值
        print(futureValue);
      })
    

    (6)在之前iOS代理方法中就可以回调func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult)

    func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
            if call.method == "flutterCalliOS" {
                //传给flutter的值
                result();
            } else {
                result(FlutterMethodNotImplemented)
            }
        }
    

    3、Flutter简易登录界面开发

    (1)pubspec.yaml文件处理,这里集成以下框架。记得pub upgrade

    dependencies:
      flutter:
        sdk: flutter
      #风格样式
      cupertino_icons: ^1.0.2
      #状态管理
      provider: ^6.0.2
      #  #Toast
      fluttertoast: ^8.0.9
      #  #Loading框
      flutter_spinkit: ^5.1.0
    

    (2)使用Provider状态管理,提供set、get方法给外部调用

    class Counter with ChangeNotifier, DiagnosticableTreeMixin {
    
      /// 手机号
      String _phoneNum = "";
      /// 验证码
      String _codeNum  = "";
      /// 验证码发送状态0:不可点击,1:可发送,2:已发送
      int _codeSendStatus = 0; 
      /// 倒计时剩余时间
      int _leftTime = 60;
      /// 是否勾选协议
      int _protocolAllowed = 0;
    
      String get phoneNum => _phoneNum;
      String get codeNum  => _codeNum;
      int get codeSendStatus => _codeSendStatus;
      int get leftTime      => _leftTime;
      int get protocolAllowed => _protocolAllowed;
    
    
      void updatePhone({required String phone}) {
        _phoneNum = phone;
        if (_codeSendStatus != 2) {
          _leftTime = 60;
          _codeSendStatus = (phoneNum.length == 11) ? 1 : 0;
        }
        notifyListeners();
      }
    
      void updateCode({required String code}) {
        _codeNum = code;
        if (_codeSendStatus != 2) {
          _codeSendStatus = (phoneNum.length == 11) ? 1 : 0;
        }
        notifyListeners();
      }
    
      void updateSendStatus({required int status}) {
        _codeSendStatus = status;
        notifyListeners();
      }
    
      void updateLeftTime({required int left}) {
        _leftTime = left;
        notifyListeners();
      }
    
      void updateProtocolAllowed({required int allow}) {
        _protocolAllowed = allow;
        print("allow $allow");
        notifyListeners();
      }
    
      @override
      void debugFillProperties(DiagnosticPropertiesBuilder properties) {
        // TODO: implement debugFillProperties
        super.debugFillProperties(properties);
        properties.add(StringProperty('phoneNum', phoneNum));
        properties.add(StringProperty('codeNum', codeNum));
        properties.add(IntProperty('codeSendStatus', codeSendStatus));
        properties.add(IntProperty('leftTime', leftTime));
        properties.add(IntProperty('protocolAllowed', protocolAllowed));
      }
    }
    

    (3)登录界面开发,代码太多,只放部分有和原生交互的。

    ///Flutter调用原生获取验证码
    
    Future requestPhoneCode({phone:String}) async {
      var result;
      try {
        result = await platform.invokeMethod('flutterCalliOS',
            {"function":"phoneCode", "params":"{\"phone\":\"$phone\"}"});
        return Future.value(result);
      } on PlatformException catch(e) {
        return Future.error(e.toString());
      }
    }
    
    LoginTxt(
      key: codeTxtKey, 
      leftTitle: "验证码",
      showClearBtn: true,
      showCountDown: true, hintText: "输入验证码", textChangeCallBack: (code) {
        codeNum = code;
        context.read<Counter>().updateCode(code: code);
      }, maxLength: 4, clearCB: (){
        codeNum = "";
        context.read<Counter>().updateCode(code: "");
      }, sendCodeCB: () async{
        tLoadingShow(context, "发送中...");
        var val = await requestPhoneCode(phone: phoneNum);
        tLoadingDismiss(context);
        codeTxtKey.currentState!.beginCountDown();
        if (val == "1") {
          tToast(context, "验证码已发送");
        } else {
          tToast(context, "验证码发送失败");
        }
      },)
    
    ///Flutter返回原生
    Future dismissPage() async {
      var result;
      try {
        result = await platform.invokeMethod('flutterCalliOS',
            {'function':'dismiss'});
        return Future.value(result);
      } on PlatformException catch(e) {
        return Future.error(e.toString());
      }
    }
    tyTextButtonFactory(
      Text(""),
      tyTransparentColor(), () async{
      var futureValue = await dismissPage();
      print(futureValue);
    })
    

    (4)交互效果

    flutterDemo.gif

    4、思考

    在已有的项目中集成Flutter,业务耦合性低比如交互少、业务关联小的模块,可以考虑。

    相关文章

      网友评论

          本文标题:在iOS原生项目中集成Flutter登录界面

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