Flutter与Android(Java)通讯

Flutter代码

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

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        '/widget': (_) => flutterWebviewPlugin,
      },
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  //步骤1
  static const platform = const MethodChannel('cn.mrlong.flutterplayer/plugin');
  String _returnData = '==';

  Future<Null> _jumpToNative() async {
    String returnData = await platform.invokeMethod('dataInteraction');
    setState(() {
      _returnData = returnData;
    });
  }

  Future<Null> _jumpToNativeWithValue() async {
    String result =
        await platform.invokeMethod('dataInteraction', "这个来源于Flutter");
    setState(() {
      _returnData = result;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                _jumpToNative();
              },
              child: Text('Flutter2Android'),
            ),
            RaisedButton(
              onPressed: () {
                _jumpToNativeWithValue();
              },
              child: Text('Flutter2Android带参数'),
            ),
            Text(
              _returnData,
              style: TextStyle(color: Colors.red),
            )
          ],
        ),
      ),
    );
  }
}

Android代码

package cn.mrlong.flutterplayer;

import android.os.Bundle;
import android.widget.Toast;

import java.util.Random;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;


public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "cn.mrlong.flutterplayer/plugin";

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

        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(new MethodCallHandler() {
            @Override
            public void onMethodCall(MethodCall call, Result result) {
                if (call.method.equals("dataInteraction")) {
                    //获取来自于Flutter的数据
                    if (null != call.arguments)
                        Toast.makeText(MainActivity.this, "Java收到:" + call.arguments.toString(), Toast.LENGTH_SHORT).show();
                    int data = getData();
                    //返回数据
                    result.success("来源java平台:" + data);
                } else {
                    result.notImplemented();
                }
            }
        });

        GeneratedPluginRegistrant.registerWith(this);
    }

    private int getData() {
        Random random = new Random();
        return random.nextInt(1000);
    }
}

    原文作者:wasdzy111
    原文地址: https://www.jianshu.com/p/8e339eb9665c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞