flutter-android调用dart android原生启动flutter界面

package com.topway.cms;

import android.os.Bundle;
import android.text.TextUtils;

import com.topway.FlutterNativePlugin;
import com.topway.bean.MyEvent;
import com.topway.utils.MyLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {
    public static String CHANNEL = "com.native/openLogin";
    EventChannel.EventSink mySink;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);
        FlutterNativePlugin.registerWith(this.registrarFor(FlutterNativePlugin.CHANNEL));
        EventBus.getDefault().register(this);
        native2Dart();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MyEvent myEvent) {
        if (TextUtils.equals("openLogin", myEvent.getType())) {
            mySink.success("haha");

        }
    }

    private void native2Dart() {
        EventChannel eventChannel = new EventChannel(getFlutterView(), CHANNEL);
        EventChannel.StreamHandler streamHandler = new EventChannel.StreamHandler() {
            // 这个onListen是Flutter端开始监听这个channel时的回调,第二个参数 EventSink是用来传数据的载体。
            @Override
            public void onListen(Object o, EventChannel.EventSink eventSink) {
                MyLog.log("onListen被调用" + o.toString());
                mySink = eventSink;
            }

            // 对面不再接收
            @Override
            public void onCancel(Object o) {
                MyLog.log("onCancel被调用");
            }
        };
        eventChannel.setStreamHandler(streamHandler);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
class _MyHomePageState extends State {
  bool animate;

  //用数据流实现与native通信。超时后,去启动登录页
  static const EventChannel eventChannel = EventChannel('com.native/openLogin');

  @override
  void initState() {
    super.initState();
    eventChannel
        .receiveBroadcastStream(['arg1']).listen(_onEvent, onError: _onError);
  }

  void _onEvent(Object event) {
    print('_onevent:' + event);
    //此处超时启动登录页,需要关闭其他所有页
    Navigator.push(
        context, new MaterialPageRoute(builder: (context) => new LoginPage()));
  }

  void _onError(Object error) {
    print('出错了' + error);
  }

  @override
  Widget build(BuildContext context) {

.......。。。。。。。。。。。。。。。。。

你可能感兴趣的:(Flutter)