在iOS原生項(xiàng)目中集成Flutter登錄界面

1、已有項(xiàng)目工程(iOS)集成Flutter

(1)關(guān)閉Bitcode,cd到iOS工程最外層,在終端輸入生成flutter工程

flutter create -t module flutter_project

結(jié)束后項(xiàng)目結(jié)構(gòu)如下

- flutter_project
-- lib
--- main.dart

- iOS_project
-- .xcworkspace

(2)Podfile文件示例,在{}內(nèi)分別填入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項(xiàng)目名稱}' do
install_all_flutter_pods(flutter_application_path)
end

2、iOS項(xiàng)目和Flutter文件的相互調(diào)用

(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工程新建一個(gè)類TYFlutter聲明通道,注冊(cè)代理回調(diào),通道名為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)原生跳轉(zhuǎn)Flutter頁(yè)面

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調(diào)用原生,F(xiàn)lutter工程新建一個(gè).dart文件flutter 調(diào)用 原生的函數(shù),通道名也是flutter_channel

const platform =  const MethodChannel('flutter_channel');

/// 路由
/// 返回上一級(jí)
Future dismissPage() async {
  var result;
  try {
    //傳遞給原生的方法名和參數(shù)
    result = await platform.invokeMethod('flutterCalliOS',
        {'function':'dismiss'});
    //接收原生傳過(guò)來(lái)的值
    return Future.value(result);
  } on PlatformException catch(e) {
    return Future.error(e.toString());
  }
}

(5)Flutter開始調(diào)用聲明的函數(shù),比如在flutter頁(yè)面點(diǎn)擊返回

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

(6)在之前iOS代理方法中就可以回調(diào)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簡(jiǎn)易登錄界面開發(fā)

(1)pubspec.yaml文件處理,這里集成以下框架。記得pub upgrade

dependencies:
  flutter:
    sdk: flutter
  #風(fēng)格樣式
  cupertino_icons: ^1.0.2
  #狀態(tài)管理
  provider: ^6.0.2
  #  #Toast
  fluttertoast: ^8.0.9
  #  #Loading框
  flutter_spinkit: ^5.1.0

(2)使用Provider狀態(tài)管理,提供set、get方法給外部調(diào)用

class Counter with ChangeNotifier, DiagnosticableTreeMixin {

  /// 手機(jī)號(hào)
  String _phoneNum = "";
  /// 驗(yàn)證碼
  String _codeNum  = "";
  /// 驗(yàn)證碼發(fā)送狀態(tài)0:不可點(diǎn)擊,1:可發(fā)送,2:已發(fā)送
  int _codeSendStatus = 0; 
  /// 倒計(jì)時(shí)剩余時(shí)間
  int _leftTime = 60;
  /// 是否勾選協(xié)議
  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)登錄界面開發(fā),代碼太多,只放部分有和原生交互的。

///Flutter調(diào)用原生獲取驗(yàn)證碼

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: "驗(yàn)證碼",
  showClearBtn: true,
  showCountDown: true, hintText: "輸入驗(yàn)證碼", textChangeCallBack: (code) {
    codeNum = code;
    context.read<Counter>().updateCode(code: code);
  }, maxLength: 4, clearCB: (){
    codeNum = "";
    context.read<Counter>().updateCode(code: "");
  }, sendCodeCB: () async{
    tLoadingShow(context, "發(fā)送中...");
    var val = await requestPhoneCode(phone: phoneNum);
    tLoadingDismiss(context);
    codeTxtKey.currentState!.beginCountDown();
    if (val == "1") {
      tToast(context, "驗(yàn)證碼已發(fā)送");
    } else {
      tToast(context, "驗(yàn)證碼發(fā)送失敗");
    }
  },)
///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、思考

在已有的項(xiàng)目中集成Flutter,業(yè)務(wù)耦合性低比如交互少、業(yè)務(wù)關(guān)聯(lián)小的模塊,可以考慮。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容