flutter与native交互
Posted suyue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flutter与native交互相关的知识,希望对你有一定的参考价值。
flutter与native交互
一、dart
- 引入包 import \'package:flutter/services.dart\';
- 定义通道名并通过 MethodChannel连接
- 调用native方法platform.invokeMethod("call_native_method")
`
import \'package:flutter/material.dart\';
import \'package:flutter/widgets.dart\';
import \'dart:async\';
//与原生交互
import \'package:flutter/services.dart\';
class MinePage extends StatefulWidget {
@override
_MinePageState createState() => _MinePageState();
}
class _MinePageState extends State<MinePage> {
static const CHANNEL_NAME = "samples.flutter.study/call_native";
static const platform = MethodChannel(CHANNEL_NAME);
String _res = "111";
@override
Widget build(BuildContext context) {
return Column(
children: [
RaisedButton(
onPressed: () async{
String res = await platform.invokeMethod("call_native_method");
setState(() {
_res = res;
});
},
child:Text("调用native")
),
Text(_res),
],
);
}
}
`
二、native(安卓)
- 引用相关flutter包
- 继承FlutterActivity类,通过MethodChannel连接相同的通道名称
- 写交互的方法
·
package com.example.flutter_app;
import android.content.Context;
import android.os.BatteryManager;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
public class MainActivity extends FlutterActivity {
String CHANNEL_NAME = "samples.flutter.study/call_native";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MethodChannel(getFlutterView(),CHANNEL_NAME).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall,MethodChannel.Result result){
if(methodCall.method.equals("call_native_method")){
result.success("native返回值aaa");
} else {
result.success("I don not know what you said");
}
};
}
);
};
}
·
以上是关于flutter与native交互的主要内容,如果未能解决你的问题,请参考以下文章
Flutter 如何与 Native (Android) 进行交互 | 开发者说·DTalk
Flutter 如何与 Native (Android) 进行交互 | 开发者说·DTalk
错误记录Flutter 混合开发获取 BinaryMessenger 报错 ( FlutterActivityAndFragmentDelegate.getFlutterEngine() )(代码片段