原生Android调用Flutter的dart方法

先提供完整的代码

main.dart

import 'package:flutter/material.dart';

import 'MainPage.dart';

void main(){
  runApp(
     MyApp()
  );
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'default',
      theme: defaultTheme,
      home: MainPage(),
    );
  }
}


final ThemeData defaultTheme = ThemeData(
    primaryColor: Colors.lightBlue
);

MainPage.dart

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

class MainPage extends StatefulWidget{
  @override
  MainPageState createState()  => MainPageState();
}

class MainPageState extends State{

  static const _platform = const MethodChannel('toFlutterChannelName');

  @override
  void initState() {
    _platform.setMethodCallHandler(flutterMethod);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter调用原生Android的方法',
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter调用原生Android的Java方法'),
        ),
        body: Center(
          child:
          RaisedButton(
            child:
            Padding(
              padding: EdgeInsets.only(left: 20,right: 20,top: 20,bottom: 20),
              child: Text('点击按钮调用原生Android的Java方法\n,返回值在控制台输出'),
            ),

            onPressed: ()async{
              const platform = const MethodChannel("toJava");
              String returnValue = await platform.invokeMethod("张三");
              print("从原生Android的java方法返回的值是:"+returnValue);
            },
          )
        )
      ),
    );
  }



  Future flutterMethod(MethodCall methodCall) async{
    switch (methodCall.method) {
      case 'fluMethod':
        print('原生Android调用了flutterMethod方法!!!');
        print('原生Android传递给flutter的参数是::'+methodCall.arguments);
        break;
    }
  }

}

 

MainActivity.java

package com.example.flutterTojava;

import android.os.Bundle;
import android.os.StrictMode;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.BinaryMessenger;
//import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {

    private static final String channel = "toJava";

    MethodChannel methodChannel_toFlutter;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        //新版的Flutter SDK默认使用的是 import io.flutter.embedding.android.FlutterActivity; 包,
        // 则在MethodChannel方法中的第一个参数填写 getFlutterEngine().getDartExecutor().getBinaryMessenger()
        //如果你使用的Flutter的SDK是旧版本,那么默认的是 import io.flutter.app.FlutterActivity; 包
        // 则MethodChannel方法中的第一个参数填写 getFlutterView()

        new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(),channel).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
                        if (methodCall.method!=null) {
                            result.success(toJava(methodCall.method));
                        } else {
                            result.notImplemented();
                        }
                    }
                }
        );


        methodChannel_toFlutter = new MethodChannel(
                getFlutterEngine().getDartExecutor().getBinaryMessenger(), "toFlutterChannelName"
        );

    }


    public String toJava(String name){
        System.out.println("传递的参数是"+name);
        invokeFlutterMethod_toAllFlutter();
        return "您好"+name;
    }

    public void invokeFlutterMethod_toAllFlutter(){
        if (this.methodChannel_toFlutter != null) {
            this.methodChannel_toFlutter.invokeMethod("fluMethod", "我是原生Android,我将参数传递给Flutter里面的一个方法", new MethodChannel.Result() {
                @Override
                public void success(Object o) {

                }
                @Override
                public void error(String s, String s1, Object o) {
                }
                @Override
                public void notImplemented() {
                }
            });
        }
    }

}

 

 

下面来解释步骤

一、在MainPage类中定义一个MethodChannel常量_platform, 并在initState()方法中处理Flutter申请要调用的method的值,此时会调用自定义方法flutterMethod

在Flutter代码中:

  static const _platform = const MethodChannel('toFlutterChannelName');

  @override
  void initState() {
    _platform.setMethodCallHandler(flutterMethod);
    super.initState();
  }

二、定义一个flutterMethod方法

在Flutter代码中:

  Future flutterMethod(MethodCall methodCall) async{
    switch (methodCall.method) {
      case 'fluMethod':
        print('原生Android调用了flutterMethod方法!!!');
        print('原生Android传递给flutter的参数是::'+methodCall.arguments);
        break;
    }
  }

三、在原生Android的MainActivity类中,声明一个MethodChannel的变量,然后在onCreate()方法中,通过这个变量获取通道

public class MainActivity extends FlutterActivity {

    MethodChannel methodChannel_toFlutter;

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

         methodChannel_toFlutter = new MethodChannel(
                getFlutterEngine().getDartExecutor().getBinaryMessenger(),"toFlutterChannelName"
         );

    }

}

四、让原生Android调用 invokeFlutterMethod_toAllFlutter() 方法,这个方法里面实现了 "调用flutter方法的动作"。

您也可以在onCreate() 里面,直接invokeFlutterMethod_toAllFlutter()调用这个方法,以调用flutter的方法。

public void invokeFlutterMethod_toAllFlutter(){
        if (this.methodChannel_toFlutter != null) {
            this.methodChannel_toFlutter.invokeMethod("fluMethod", "我是原生Android,我将参数传递给Flutter里面的一个方法", new MethodChannel.Result() {
                @Override
                public void success(Object o) {

                }
                @Override
                public void error(String s, String s1, Object o) {
                }
                @Override
                public void notImplemented() {
                }
            });
        }
    }

五、测试

原生Android调用Flutter的dart方法_第1张图片

你可能感兴趣的:(Flutter与Android,交互,跨语言交互)