-
使用平臺(tái)通道在客戶端(Flutter)和宿主平臺(tái)之間傳遞消息,如下圖:
PlatformChannels.png
消息和響應(yīng)時(shí)異步傳遞的赡矢,以確保用戶界面保持響應(yīng)(不會(huì)掛起)
首先烦却,我們用MethodChannel構(gòu)建通道蹦误。
Flutter和宿主通過(guò)通道進(jìn)行連接咱筛,單個(gè)應(yīng)用的使用的通道名稱必須是唯一的;官方建議通道名稱前加一個(gè)唯一的“域名前綴”
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'package:flutter/cupertino.dart';
class PlatformChannelState extends State<PlatformChannelPage>{
static const platform = const MethodChannel(/*通道名稱*/'com.lei.io/userdefault');
// ……
}
構(gòu)建視圖代碼:兩個(gè)按鈕嫌佑,一個(gè)text用來(lái)顯示傳回來(lái)的值
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: AppBar(
title: new Text("paltform channel"),
),
body:Column(
children: <Widget>[
new FlatButton(
onPressed: (){
setPlatformUserDefaultInfo(context);
},
child: new Text("存儲(chǔ)"),
color: Colors.green,
),
new FlatButton(
onPressed: (){
getPlatformUserDefaultInfo();
},
child: new Text("讀取"),
color: Colors.green,
),
new Text(_platString)
],
),
);
}
傳輸數(shù)據(jù)到swift豆茫,swift返回bool值
Future<Null> setPlatformUserDefaultInfo(BuildContext context) async{
bool platresult;
try{
// 第一參數(shù)是“方法名”,第二個(gè)參數(shù)是方法的參數(shù)
platresult = await platform.invokeMethod('setToken',"我是一個(gè)token",);
} on PlatformException catch(e){
}
// 彈出一個(gè)ios風(fēng)格的彈出框
showCupertinoDialog(
context:context,
builder:(BuildContext context){
return new CupertinoAlertDialog(
content: new Text("設(shè)置成功"),
actions: <Widget>[
FlatButton(
child: new Text("確定"),
onPressed:(){
Navigator.pop(context);
},
)
],
);
}
);
從iOS獲取值
Future<Null> 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*/"我是一個(gè)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))
}
}
參數(shù)對(duì)照表:
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