【Flutter】flutter与原生交互-swift

flutter代码

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

  //交互的通道名称,flutter和native是通过这个标识符进行相互间的通信
  static const communicateChannel = MethodChannel('https://www.oyear.cn');

  //异步执行调用原生方法,保持页面不卡住,因为调用原生的方法可能没实现会抛出异常,所以trycatch包住
  Future<void> _communicateFunction(flutterPara) async {
    try {
      //原生方法名为callNativeMethond,flutterPara为flutter调用原生方法传入的参数,await等待方法执行
      final result = await communicateChannel.invokeMethod(
          'callNativeMethond', flutterPara);
      //如果原生方法执行回调传值给flutter,那下面的代码才会被执行
      _nativeCallBackValue = result;
      setState(() {});
    } on PlatformException catch (e) {
      //抛出异常
      //flutter: PlatformException(001, 进入异常处理, 进入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("我是原生返回数据")
        }else{
            result(FlutterMethodNotImplemented)
        }
    }
    
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

猜你喜欢

转载自blog.csdn.net/tianzhilan0/article/details/107634423