当前位置:   article > 正文

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

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
    }()

}

  • 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
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

######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<MyHomePage> {
//  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: <Widget>[
              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<void> _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);
    }
  }

}

  • 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
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115

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

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号