Flutter與原生Android雙向交互

項(xiàng)目地址(github


1、Flutter調(diào)用原生Android的api


(1)自定義插件FlutterToAndroidPlugins,實(shí)現(xiàn)MethodChannel.MethodCallHandler
public class FlutterToAndroidPlugins implements MethodChannel.MethodCallHandler{

    private FlutterActivity activity;

    private FlutterToAndroidPlugins(FlutterActivity activity) {
        this.activity = activity;
    }

    public static void registerWith(FlutterActivity activity) {
        FlutterToAndroidPlugins instance = new FlutterToAndroidPlugins(activity);
        //flutter調(diào)用原生
        MethodChannel channel = new MethodChannel(activity.registrarFor(DealMethodCall.channels_flutter_to_native)
                .messenger(), DealMethodCall.channels_flutter_to_native);
        //setMethodCallHandler在此通道上接收方法調(diào)用的回調(diào)
        channel.setMethodCallHandler(instance);
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        DealMethodCall.onMethodCall(activity, methodCall, result);
    }
(2)DealMethodCall類處理業(yè)務(wù)
class DealMethodCall {
    /**
     * 通道名稱,必須與flutter注冊的一致
     */
    static final String channels_flutter_to_native = "com.bhm.flutter.flutternb.plugins/flutter_to_native";
 
    /**
     * 方法名稱,必須與flutter注冊的一致
     */
    private static final HashMap<String, String> methodNames = new HashMap<String, String>(){
        {
            put("register", "register");
        }
    };

    /** flutter調(diào)用原生方法的回調(diào)
     * @param activity activity
     * @param methodCall methodCall
     * @param result result
     */
    static void onMethodCall(FlutterActivity activity, MethodCall methodCall, final MethodChannel.Result result){
        if(methodNames.get("register").equals(methodCall.method)){//注冊賬號
            //此處處理業(yè)務(wù)(線程)
            result.success(object);//處理后回調(diào)給Flutter
        }
    }
(3)Android中的MainActivity添加注冊
@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
    FlutterToAndroidPlugins.registerWith(this);
  }
(4)Flutter項(xiàng)目中添加類InteractNative
class InteractNative {
  /* 通道名稱,必須與原生注冊的一致*/
  static const flutter_to_native = const MethodChannel(
      'com.bhm.flutter.flutternb.plugins/flutter_to_native');

  /*
   * 方法名稱,必須與flutter注冊的一致
   */
  static final Map<String, String> methodNames = const {
    'register': 'register',
  };

  /*
  * 調(diào)用原生的方法(帶參)
  */
  static Future<dynamic> goNativeWithValue(String methodName,
      [Map<String, String> map]) async {
    if (null == map) {
      dynamic future = await flutter_to_native.invokeMethod(methodName);
      return future;
    } else {
      dynamic future = await flutter_to_native.invokeMethod(methodName, map);
      return future;
    }
  }
}
(5)Flutter項(xiàng)目中需要調(diào)用原生Android的地方,使用
Map<String, String> map = {"username": username, "password": password};
    InteractNative.goNativeWithValue(InteractNative.methodNames['register'], map)
        .then((success) {
      if (success == true) {
        DialogUtil.buildToast('注冊成功');
        Navigator.pop(context);
      } else if (success is String) {
        DialogUtil.buildToast(success);
      } else {
        DialogUtil.buildToast('注冊失敗');
      }
    });


2、原生Android調(diào)用Flutter的api


(1)自定義插件AndroidToFlutterPlugins,實(shí)現(xiàn)EventChannel.StreamHandler
public class AndroidToFlutterPlugins implements EventChannel.StreamHandler{

    private FlutterActivity activity;

    private AndroidToFlutterPlugins(FlutterActivity activity) {
        this.activity = activity;
    }

    public static void registerWith(FlutterActivity activity) {
        AndroidToFlutterPlugins instance = new AndroidToFlutterPlugins(activity);
        //原生調(diào)用flutter
        EventChannel eventChannel = new EventChannel(activity.registrarFor(DealMethodCall.channels_native_to_flutter)
                .messenger(), DealMethodCall.channels_native_to_flutter);
        eventChannel.setStreamHandler(instance);
    }

    @Override
    public void onListen(Object o, EventChannel.EventSink eventSink) {
        DealMethodCall.onListen(activity, o, eventSink);
    }

    @Override
    public void onCancel(Object o) {
        DealMethodCall.onCancel(activity, o);
    }
}
(2)DealMethodCall類處理業(yè)務(wù)
class DealMethodCall {

    /**
     * 通道名稱,必須與flutter注冊的一致
     */
    static final String channels_native_to_flutter = "com.bhm.flutter.flutternb.plugins/native_to_flutter";

   /**原生調(diào)用flutter方法的回調(diào)
     * @param activity activity
     * @param o o
     * @param eventSink eventSink
     */
    static void onListen(FlutterActivity activity, Object o, EventChannel.EventSink eventSink){
        //在此調(diào)用
       eventSink.success("onConnected");
 
    }

    /**原生調(diào)用flutter方法的回調(diào)
     * @param activity activity
     * @param o o
     */
    static void onCancel(FlutterActivity activity, Object o) {

    }
(3)Android中的MainActivity添加注冊
@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
    AndroidToFlutterPlugins.registerWith(this);
  }
(4)Flutter項(xiàng)目中添加類InteractNative
class InteractNative {
  /* 通道名稱,必須與原生注冊的一致*/
  static const native_to_flutter = const EventChannel(
      'com.bhm.flutter.flutternb.plugins/native_to_flutter');

 /*
  * 原生回調(diào)的方法(帶參)
  */
  static Stream<dynamic> dealNativeWithValue(){
    Stream<dynamic> stream = native_to_flutter.receiveBroadcastStream();
    return stream;
  }
}
(5)Flutter項(xiàng)目中使用
class _MyHomePageState extends State<MyHomePage> {
  StreamSubscription _subscription = null;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (null == _subscription) {
      _subscription = InteractNative.dealNativeWithValue()
          .listen(_onEvent, onError: _onError);
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if (_subscription != null) {
      _subscription.cancel();
    }
  }

  void _onEvent(Object event) {
    if ('onConnected' == event) {    
//        DialogUtil.buildToast('已連接');
    } 
  }

  void _onError(Object error) {
    DialogUtil.buildToast(error.toString());
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容