当前位置:   article > 正文

【Flutter】flutter与原生交互-swift_flutter 与ios原生通信swift call.arguments取值

flutter 与ios原生通信swift call.arguments取值

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))
          ],
        ));
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

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)
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/383187
推荐阅读
相关标签
  

闽ICP备14008679号