Flutter与Android原生界面交互
2019-04-25 本文已影响1人
习惯了_就好
Flutter代码
class SendToApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return SendToAppState();
}
}
class SendToAppState extends State<SendToApp> {
//1.定义MethodChannel,参数要与原生app中MethodChannel的参数一致,可以任意写
MethodChannel methodChannel = MethodChannel('song.test.com.myapplication');
String result = "";
void onClick() async {
//3.调用原生方法,showToast传给原生app中MethodChannel方法,MethodCall根据这个值处理不同逻辑,result原生方法的返回值
final String result = await methodChannel.invokeMethod('showToast');
setState(() {
this.result = result;
});
}
//2.编写页面
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Flutter与原生界面交互"),
),
body: Container(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(result),
RaisedButton(
onPressed: onClick,
child: Text("点击"),
)
],
)
),
)
),
);
}
}
Android原生代码
public class FlutterShowActivity extends AppCompatActivity {
FlutterView flutterView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String router = getIntent().getStringExtra("router");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//这个方法也太慢了
flutterView = Flutter.createView(
FlutterShowActivity.this,
getLifecycle(),
// "route1"//路由信息,可以传递到flutter,判断显示什么组件,也可以传递一些简单的数据
router
);
setContentView(flutterView);
//监听Flutter中的方法调用,song.test.com.myapplication跟Flutter中的参数一样
new MethodChannel(flutterView, "song.test.com.myapplication").setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("showToast")) {
Toast.makeText(FlutterShowActivity.this, "Flutter让我弹出Toast", Toast.LENGTH_SHORT).show();
result.success("APP回应Flutter已经弹过Toast了");
} else {
result.notImplemented();
}
}
}
);
}
}, 100);
}
}