swift 实现flutter基本交互 - 传值篇

iOS 为现有工程接入flutter-基础配置篇

Flutter-Api

Flutter框架基础

Demo地址

本文是在原生项目已经接入flutter的基础上进行交互传值,如果你还未接入flutter,你可以通过顶部链接去进行接入
  • 本文主要实现内容为 swift和flutter互相传值
  • 核心传值方法类似webview传值中通过桥接方式实现
swift 工程代码,以vc示例
import UIKit
import Flutter

class ViewController: UIViewController {

    let array = ["crs","grs","nrs"]
    let callName = "callNativeMethond"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.view.addSubview(button)
    }
    
    @objc func didSelectButtonClick() {
        let flutter = FlutterViewController.init()
        flutter.navigationItem.title = "Flutter-iOSTest-Demo"
        // 要与main.dart中一致
        let channelName = "com.pages.flutter.iOSTest.demo"
        let messageChannel = FlutterMethodChannel.init(name: channelName, binaryMessenger: flutter)
        messageChannel.setMethodCallHandler { [weak self] (fc, fr) in
            guard let strongSelf = self else { return }
            // call.method 获取 flutter 给回到的方法名,要匹配到 channelName 对应的多个 发送方法名,一般需要判断区分
            // call.arguments 获取到 flutter 给到的参数,(比如跳转到另一个页面所需要参数)
            // result 是给flutter的回调, 该回调只能使用一次
            print("flutter 给到我 method:\(fc.method) arguments:\(fc.arguments)")
            if fc.method == strongSelf.array[2] {
                strongSelf.dismiss(animated: true, completion: {
                    print("dissmiss end of flutter")
                })
            }
            if fc.method == strongSelf.array[1] {
                fr("flutter back source")
            }
            if fc.method == strongSelf.callName {
                fr("swift 传值成功")
            }
        }
        
        
        self.present(flutter, animated: true) {
            print("end of flutter present")
        }
//        self.navigationController?.pushViewController(flutter, animated: true)
    }
    
    lazy var button : UIButton = {
        let object = UIButton()
        object.backgroundColor = UIColor.red
        object.center = CGPoint.init(x: UIScreen.main.bounds.size.width/2, y: UIScreen.main.bounds.size.height/2)
        object.bounds = CGRect.init(x: 0, y: 0, width: 200, height: 200)
        object.addTarget(self, action: #selector(didSelectButtonClick), for: .touchUpInside)
        return object
    }()

}

flutter 工程代码,以main.dart示例
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
//  int _counter = 0;

  List widgets = ['crs','grs','nrs'];
  // 创建一个给native的channel (类似iOS的通知)
  static const methodChannel = const MethodChannel('com.pages.flutter.iOSTest.demo');
  String _nativeCallBackValue = '等待原生传值';

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: getBody()
    );
  }

  getBody() {

    return getListView();
  }

  ListView getListView() => ListView.builder(
    itemCount: widgets.length,
    itemBuilder: (BuildContext context,int position) {

      return getColum(position);
    }
  );


  Widget getColum(int i) {
    return GestureDetector(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Card(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(3.0)),
          ),
          elevation: 5.0,
          child: Column(
            children: [
              Text(
                "${widgets[i]}",
                style: TextStyle(
                  color: Colors.red,
                  fontSize: 13,
                ),
              ),
              MaterialButton(
                color: Colors.cyan,
                child: Text(_nativeCallBackValue),
                onPressed: () {
                  _communicateFunction('flutter开始传值');
                  setState(() {});

                },
              )
            ],
          )
        ),

      ),
      onTap: () {
        methodChannel.invokeMethod(widgets[i],'123456');
        print(widgets[i]);

      },
    );
  }

  Future _communicateFunction(flutterPara) async {
    try {
      //原生方法名为callNativeMethond,flutterPara为flutter调用原生方法传入的参数,await等待方法执行
      final result = await methodChannel.invokeMethod('callNativeMethond', flutterPara);
      //如果原生方法执行回调传值给flutter,那下面的代码才会被执行
      _nativeCallBackValue = result;
    } on PlatformException catch (e) {//抛出异常
      //flutter: PlatformException(001, 进入异常处理, 进入flutter的trycatch方法的catch方法)
      print(e);
    }
  }

}

相关注释已添加,有问题可以评论区留言,

Demo地址

你可能感兴趣的:(swift 实现flutter基本交互 - 传值篇)