【Flutter】flutter與原生交互-swift

flutter代碼

class _MyHomePageState extends State<MyHomePage> {
  String _nativeCallBackValue = '等待原生傳值';

  //交互的通道名稱,flutter和native是通過(guò)這個(gè)標(biāo)識(shí)符進(jìn)行相互間的通信
  static const communicateChannel = MethodChannel('https://www.oyear.cn');

  //異步執(zhí)行調(diào)用原生方法,保持頁(yè)面不卡住,因?yàn)檎{(diào)用原生的方法可能沒(méi)實(shí)現(xiàn)會(huì)拋出異常,所以trycatch包住
  Future<void> _communicateFunction(flutterPara) async {
    try {
      //原生方法名為callNativeMethond,flutterPara為flutter調(diào)用原生方法傳入的參數(shù),await等待方法執(zhí)行
      final result = await communicateChannel.invokeMethod(
          'callNativeMethond', flutterPara);
      //如果原生方法執(zhí)行回調(diào)傳值給flutter,那下面的代碼才會(huì)被執(zhí)行
      _nativeCallBackValue = result;
      setState(() {});
    } on PlatformException catch (e) {
      //拋出異常
      //flutter: PlatformException(001, 進(jìn)入異常處理, 進(jìn)入flutter的trycatch方法的catch方法)
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: ListView(
          children: <Widget>[
            InkWell(
                onTap: () {
                  _communicateFunction({"type": "221133"});
                },
                child: Container(child: Text("與原生交互"))),
            Container(child: Text(_nativeCallBackValue))
          ],
        ));
  }
}

swift代碼

@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    
    let controller = self.window.rootViewController as! FlutterViewController
    let channel = FlutterMethodChannel.init(name: "https://www.oyear.cn", binaryMessenger: controller as! FlutterBinaryMessenger)
    channel.setMethodCallHandler { (call, result) in
        if call.method == "callNativeMethond" {
            let para = call.arguments
            print(para!)
            
            result("我是原生返回?cái)?shù)據(jù)")
        }else{
            result(FlutterMethodNotImplemented)
        }
    }
    
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容