項目的一些網絡請求的數據,在原生層都以及實現,現在想把數據在Flutter層展示出來,這裏就會用到MethodChannel
第一步:
在原生層註冊:
private MethodChannel methodChannel;//聲明
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
methodChannel = new MethodChannel(getFlutterEngine().getDartExecutor(),"com.flutter.io/data");
//flutterView 通過getFlutterEngine().getDartExecutor()獲得
methodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if(methodCall.method.equals("getCamera")){
Toast.makeText(getApplicationContext(),"getCamera from flutter",Toast.LENGTH_SHORT).show();
String s= "I get your request";
result.success(s);
}
}
});
第二步:
flutter層:
@override
void initState() {
super.initState();
_tabController = new TabController(length: 2, vsync: this);
platform = const MethodChannel('com.flutter.io/data');
platform.setMethodCallHandler(methodHandler);
}
Future methodHandler(MethodCall call) async {
switch (call.method) {
case "action1":
break;
}
}
_getCamera() async {
String result;
try {
result = await platform.invokeMethod('getCamera', "2");
} on PlatformException catch (e) {
result = "Failed to openCamera";
}
setState(() {
print('1111111111111111'+result.toString());
//將返回的結果展示在flutter層
});
}
然後添加一個按鈕,調用 _getCamera()函數,就可以實現向方法名 getCamera傳相應的參數
總結:
1.flutter端創建一個MethodChannel,名字要和Android端的相同,並使用MethodChannel通過唯一方法名對應調用Android原生方法。
2.Android端同樣生成一個MethodChannel,名字要和上步驟Flutter中創建的相同。繼承MethodCallHandler方法後實現onMethodCall(MethodCall call, Result result)方法,通過call拿到上步驟調用的唯一方法名實現不同的方法。