Flutter实现Android Native有Dart进行相互调用传值

搞了一整天,网上一堆半截子代码,为啥代码不贴全呢!

最近想用flutter整几个简单的页面,首先要解决的就是传参问题,下面是完整代码:

首先在Activity里:

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.MethodChannel;

public class MyFlutterActivity extends FlutterActivity {

    private static final String FLUTTER_CHANNEL = "sample.flutter.io/flutter";
    private static final String NATIVE_CHANNEL = "sample.flutter.io/native";
    MyApplication application = null;
    FlutterEngine flutterEngine;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        application = (MyApplication)getApplication();
        flutterEngine = getFlutterEngine();
        flutterEngine.getNavigationChannel().setInitialRoute("/hello");
        flutterEngine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());

        AbLogUtil.e(MyFlutterActivity.this,"flutter activity init method channel");
        MethodChannel methodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), FLUTTER_CHANNEL);
        methodChannel.setMethodCallHandler((call, result) -> {
            if (call.method.equals("callNative")) {
                result.success("callNative success");
                AbLogUtil.e(MyFlutterActivity.this,"flutter callNative success:" + call.arguments);
            } else {
                result.notImplemented();
            }
        });

        callFlutter();
    }


    public void callFlutter(){

        MethodChannel methodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), NATIVE_CHANNEL);
        methodChannel.invokeMethod("callFlutter", "11111111", new MethodChannel.Result() {

            @Override
            public void success(Object o) {
                AbLogUtil.e(MyFlutterActivity.this,"flutter callFlutter success");
            }

            @Override
            public void error(String s, String s1, Object o) {
                AbLogUtil.e(MyFlutterActivity.this,s + s1);
            }

            @Override
            public void notImplemented() {

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (flutterEngine!=null){
            flutterEngine.getLifecycleChannel().appIsResumed();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (flutterEngine!=null){
            flutterEngine.getLifecycleChannel().appIsInactive();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (flutterEngine!=null){
            flutterEngine.getLifecycleChannel().appIsPaused();
        }
    }
}

下面是Flutter里的代码:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class HelloPage extends StatefulWidget {

  HelloPage({Key? key}) : super(key: key);

  final String title = "Hello Page";

  @override
  _HelloPageState createState() => _HelloPageState();
}

class _HelloPageState extends State<HelloPage> {

  //传值
  static const flutterChannel = const MethodChannel("sample.flutter.io/flutter");
  static const nativeChannel = const MethodChannel("sample.flutter.io/native");
  String _token = "111";
  String _result = "222";

  @override
  void initState() {
    super.initState();
    //传值 设置监听
    nativeChannel.setMethodCallHandler(nativeCallHandler);
  }

  //实现监听
  Future nativeCallHandler(MethodCall call) async {
    switch (call.method) {
      case "callFlutter":
        //获取传来的值
        String arguments = call.arguments;

        //刷新
        setState(() {
          _token = arguments;
        });

        print('原生Android调用了flutter方法' + _token);
        break;
    }
  }

  Future _callNative() async {
    Map result = {'message': 'callNative'};
    try {
        _result = await flutterChannel.invokeMethod('callNative', result);
    } on PlatformException catch (e) {
        _result = "Failed: '${e.message}'.";
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children:[
            Text(_token),
            Text(_result),
            ElevatedButton(
                child: Text('调用native'),
                onPressed: _callNative,
            ),
          ],
        ),
      ),
    );
  }
}


内容来源与作者发布和网络,如有版权相关问题请及时与我们取得联系,我们将立即删除。

关于作者

ym2020 点击这里给我发消息

友情链接

  1. GitHub
  2. Twitter
  3. Facebook
在线客服