美文网首页
Native和flutter相互交互

Native和flutter相互交互

作者: 禄子_c79b | 来源:发表于2022-04-12 15:37 被阅读0次

场景:Native点击按钮跳转flutter页面并传参

Android页面

public class LoginFlutterActivity extends FlutterActivity {
    private String flutterMethodChannelName = "com.example.flutter_app/plugin";//android和Dart保持一致
    MethodChannel methodChannel_callFlutter;
    private BasicMessageChannel<Object> mBasicMessageChannel;
    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent_flutter_activity);
//最新版sdk写法
        methodChannel_callFlutter = new
          MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(), flutterMethodChannelName);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
        #//Android传参到flutter**
                Map map = new HashMap();
                map.put("content","Android进阶三部曲");
                methodChannel_callFlutter.invokeMethod("getPlatformVersion2", map, new MethodChannel.Result() {//2
                    @Override
                    public void success(Object o) {
                        Log.d(MAIN_ACTIVITY,(String)o);
                    }
                    @Override
                    public void error(String errorCode, String errorMsg, Object errorDetail) {
                        Log.d(MAIN_ACTIVITY,"errorCode:"+errorCode+" errorMsg:"+errorMsg+" errorDetail:"+(String)errorDetail);
                    }
                    @Override
                    public void notImplemented() {
                        Log.d(MAIN_ACTIVITY,"notImplemented");
                    }
                });
                 ***/
//                FlutterBoostRouteOptions options = new FlutterBoostRouteOptions.Builder()
//                        .pageName("splash")
//                        .arguments(new HashMap<>())
//                        .requestCode(1111)
//                        .build();
//                FlutterBoost.instance().open(options);
//                finish();
//方式三使用
                startActivity(FlutterActivity
                            .withCachedEngine("my_engine_id")
                        .build(LoginFlutterActivity.this));

            }
        });
    }

Dart页面

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  static const platformChannel =
   const MethodChannel('com.example.flutter_app/plugin');
  String textContent = 'Flutter端初始文字';
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    platformChannel.setMethodCallHandler((methodCall) async {
      switch (methodCall.method) {
        case 'getPlatformVersion2':
          String content = await methodCall.arguments['content'];
          if (content != null && content.isNotEmpty) {
            setState(() {
              textContent = content;
            });
            return 'Dart传递过来的msg参数';//返回给Native activity
          } else {
            throw PlatformException(
                code: 'error', message: '失败', details: 'content is null');
          }
          break;
        default:
          throw MissingPluginException();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Flutter Demo",
      home: Scaffold(
        appBar: AppBar(
          title: Text('Android调用Flutter'),
        ),
        body: Padding(
          padding: EdgeInsets.all(40.0),
          child: Text(textContent),
        ),
      ),
    );
  }
}

参照:https://www.jianshu.com/p/7692ed27f9f6

相关文章

网友评论

      本文标题:Native和flutter相互交互

      本文链接:https://www.haomeiwen.com/subject/hqfnsrtx.html