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");
}
};
}
);
};
}
·
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。