Flutter和Android交互

2019-08-16  本文已影响0人  郑永博

https://blog.csdn.net/weixin_41191134/article/details/88964411

Android端

 private void flutterAndNative() {
        FlutterView flutterView = Flutter.createView(this, getLifecycle(), "bottomView");
        BasicMessageChannel channel = new BasicMessageChannel(
                flutterView, "foo", StringCodec.INSTANCE);
// Send message to Dart and receive reply.
        channel.send("Hello, world", o -> {

        });
        channel.setMessageHandler(new BasicMessageChannel.MessageHandler() {
            @Override
            public void onMessage(Object o, BasicMessageChannel.Reply reply) {
                Toast.makeText(mContext, o.toString(), Toast.LENGTH_SHORT).show();
                reply.reply("Hi from Android");
            }
        });
        bottomContainer.addView(flutterView);
    }

flutter端

void main() => runApp(_windgetForRoute(window.defaultRouteName));

Widget _windgetForRoute(String route) {
  switch (route) {
    case "bottomView":
      return MaterialApp(
        home: Scaffold(body: BottomNavigationView()),
      );
      break;
    default:
      break;
  }
  return MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text("demo")), body: BottomNavigationView()));
}
flutterAndNative(index) async{
    const channel = BasicMessageChannel<String>('foo', StringCodec());
    final String reply = await channel.send('Hello, world$index');
    print(reply);
    channel.setMessageHandler((String message) async {
      print('Received: $message');
      return 'Hi from Dart:$index';
    });
  }
上一篇下一篇

猜你喜欢

热点阅读