Flutter调用原生Android的Java方法

一、编写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{
  @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);
            },
          )
        )
      ),
    );
  }

}

 

三、编写MainActivity类

注意事项:
新版的Flutter SDK默认使用的是 import io.flutter.embedding.android.FlutterActivity; 包,
则在MethodChannel方法中的第一个参数填写 getFlutterEngine().getDartExecutor().getBinaryMessenger()
如果你使用的Flutter的SDK是旧版本,那么默认的是 import io.flutter.app.FlutterActivity; 包
则MethodChannel方法中的第一个参数填写 getFlutterView()
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";

    @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);
        }

        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();
                        }
                    }
                }
        );
    }


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

}

 

四、控制台输出

 

你可能感兴趣的:(Flutter,Flutter与java)