第一步:android原生代码示例
a:先创建一个类(可以将不同的功能分别放到不同的类中)
class AppUtils: MethodChannel.MethodCallHandler {
companion object{
//声明注册的方法
const val CHANNEL = "huang/method"
var methodChannel: MethodChannel? =null
fun registerWith(binary: FlutterView){
methodChannel = MethodChannel(binary, CHANNEL)
methodChannel!!.setMethodCallHandler(AppUtils())
}
}
override fun onMethodCall(methodCall: MethodCall, result: MethodChannel.Result) {
if(methodCall.method.equals("getData")) {
val res: String = getData()
result.success(res)
}else {
result.notImplemented()
}
}
private fun getData(): String {
return "大家好啊,我是第一次测试"
}
}
b:在MainActivity中注册你声明的这个类
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
AppUtils.registerWith(flutterView)
}
}
第二步:书写Flutter调用代码示例
a:调用原生的Flutter方法
Future<String> testPrint() async{
const platform = const MethodChannel("huang/method");
String reslut = "---";
reslut = await platform.invokeMethod("getData");
print("输出的结果是:$reslut");
return reslut;
}
b:写一个简单的Flutter点击事件调用这方法
GestureDetector(
child: Padding(padding: const EdgeInsets.only(left: 5),
child: Text("获取验证码",style: TextStyle(fontSize: 15,color: Color(0xFFFE6040))),
),
onTap: (){
testPrint();
},
)
总结:这就是一个简单的Flutter调用原生的方法流程,比如我们接入三方登录等就可以如此操作,返回对应的结果
附录:下面这个是如果MainActivity继承的是 'io.flutter.embedding.android.FlutterActivity'包下的FlutterActivity,找不到flutterView可以换一种写法,自己定义的方法换成下面这个,传入的是FlutterEngine
class FlutterUtils : MethodChannel.MethodCallHandler{
companion object{
const val CHANNEL="huang/method"
var methodChannel : MethodChannel? = null
fun regesterWith(binary: FlutterEngine){
methodChannel = MethodChannel(binary.dartExecutor, CHANNEL)
methodChannel!!.setMethodCallHandler(FlutterUtils())
}
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method.equals("string2MD5")){
val argument = call.argument<String>("params")
Log.d("FlutterUtils","结果是:"+argument)
var res = MD5Utils.string2MD5(argument)
result.success(res)
}else{
result.notImplemented()
}
}
}
在activity中注册传入的就是
import android.os.Bundle
import com.example.flutter_app.utils.FlutterUtils
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
FlutterUtils.regesterWith(flutterEngine!!)
}
}