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,
            ),
          ],
        ),
      ),
    );
  }
}


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

 关于作者
 热门教程
通过Git下载和提交代码的命令记录
安装好git后: 1、配置邮箱 git config --global user.name ymbok git con
2023-08-15
剑道仙尊
59
通过ADB在Android系统中快捷截屏和录屏的方法
连上ADB线后: 截图 创建一个BAT文件,用于截图,直接双击运行即可将图片保存到D:\screenshot目录,提前
2023-08-15
剑道仙尊
110
Android12 源码下载与编译
下载Android12 源码 sudo apt-get update 安装curl sudo apt install
2023-04-25
剑道仙尊
125
android生成签名文件jks并获取SHA1
打开Android Studio终端,输入: keytool -genkey -alias app -keyalg R
2022-07-13
剑道仙尊
93
Flutter开发APP更改状态栏文字颜色
void main(){ runApp(MyApp()); /// 状态栏文字黑色 SystemChrome
2022-06-09
剑道仙尊
133
Android Swicth按钮样式自定义
&lt;Switch android:id="@+id/switch_btn" android:layout_wi
2022-06-07
剑道仙尊
135
Pagging3写起来太麻烦,简单封装及其简单
Pagging3分页写起来很麻烦,这里分享一下我的简化开发的方法,思路就是把获取数据的函数分离出来 首先定义一个基础的
2022-06-07
剑道仙尊
203
在项目中使用Hilt Retrofit使用总结
直接开始,首先我们看看怎么使用Hilt编写 Retrofit 接口请求类 用@Provides注解定义可注入的实例的提
2022-06-07
剑道仙尊
201
Android Jetpack Paging 3 下拉刷新和加载更多代码示例
使用Paging3实现列表的下拉刷新和加载更多 首先定义列表布局文件 &lt;androidx.swiperefres
2022-06-07
剑道仙尊
434
StatefulBuilder实现Dialog的刷新
在Flutter中使用Dialog时,因为 showDialog返回的context与当前页面的 context不是同
2022-06-07
剑道仙尊
136