Flutter和宿主平台进行数据交互(swift)

  • 使用平台通道在客户端(Flutter)和宿主平台之间传递消息,如下图:


    PlatformChannels.png

    消息和响应时异步传递的,以确保用户界面保持响应(不会挂起)

  • 首先,我们用MethodChannel构建通道。
    Flutter和宿主通过通道进行连接,单个应用的使用的通道名称必须是唯一的;官方建议通道名称前加一个唯一的“域名前缀”

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'package:flutter/cupertino.dart';

class PlatformChannelState extends State{
  static const platform = const MethodChannel(/*通道名称*/'com.lei.io/userdefault');
  // ……
}

构建视图代码:两个按钮,一个text用来显示传回来的值

Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: AppBar(
        title: new Text("paltform channel"),
      ),
      body:Column(
        children: [
          new FlatButton(
            onPressed: (){
              setPlatformUserDefaultInfo(context);
            },
            child: new Text("存储"),
            color: Colors.green,
          ),
          new FlatButton(
            onPressed: (){
              getPlatformUserDefaultInfo();
            },
            child: new Text("读取"),
            color: Colors.green,
          ),
          new Text(_platString)
        ],
      ),
    );
  }

传输数据到swift,swift返回bool值

Future setPlatformUserDefaultInfo(BuildContext context) async{
    bool platresult;
    try{
      // 第一参数是“方法名”,第二个参数是方法的参数
      platresult = await platform.invokeMethod('setToken',"我是一个token",);
    } on PlatformException catch(e){
    }
    // 弹出一个ios风格的弹出框
    showCupertinoDialog(
       context:context,
       builder:(BuildContext context){
           return new CupertinoAlertDialog(
             content: new Text("设置成功"),
             actions: [
               FlatButton(
                 child: new Text("确定"),
                 onPressed:(){
                   Navigator.pop(context);
                 },
               )
             ],
           );
       }
    );

从iOS获取值

Future getPlatformUserDefaultInfo() async{
    String platString;
    try{
      platString = await platform.invokeMethod('getToken');
    } on PlatformException catch(e){
      platString = e.message;
    }
    setState(() {
      _platString = platString;
    });
  }

iOS代码

@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)

    let controller:FlutterViewController = window.rootViewController as! FlutterViewController
    let userdefault = FlutterMethodChannel(name: "com.lei.io/userdefault", binaryMessenger: controller)
    userdefault.setMethodCallHandler { (call, result) in
        //       platresult = await platform.invokeMethod(/*cell.method*/'setToken',/*cell.arguments*/"我是一个token",);
        if "setToken" == call.method{
            self.setPlatString(result: result, tokenStr: call.arguments as! String)
        }
        else if "getToken" == call.method{
            self.getPlatString(result: result)
        }
        else{
            result(FlutterMethodNotImplemented)
        }
    }

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
    fileprivate func getPlatString(result:FlutterResult){
        let token:String = UserDefaults.standard.value(forKey: "token") as! String
        result(token)
    }
    fileprivate func setPlatString(result:FlutterResult,tokenStr:String){
        UserDefaults.standard.set(tokenStr, forKey: "token")
        UserDefaults.standard.synchronize()
        result(NSNumber(booleanLiteral: true))
    }
}

参数对照表:


Dart    Android iOS
null    null    nil (NSNull when nested)
bool    java.lang.Boolean   NSNumber numberWithBool:
int java.lang.Integer   NSNumber numberWithInt:
int, if 32 bits not enough  java.lang.Long  NSNumber numberWithLong:
int, if 64 bits not enough  java.math.BigInteger    FlutterStandardBigInteger
double  java.lang.Double    NSNumber numberWithDouble:
String  java.lang.String    NSString
Uint8List   byte[]  FlutterStandardTypedData typedDataWithBytes:
Int32List   int[]   FlutterStandardTypedData typedDataWithInt32:
Int64List   long[]  FlutterStandardTypedData typedDataWithInt64:
Float64List double[]    FlutterStandardTypedData typedDataWithFloat64:
List    java.util.ArrayList NSArray
Map java.util.HashMap   NSDictionary

参考

你可能感兴趣的:(Flutter和宿主平台进行数据交互(swift))