Flutter插件开发之FlutterChannel :Flutter调用Android 与 Android调用Flutter

  • Android 代码:
import 'dart:async';

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

typedef void EventCallback(args,args2);


class FlutterPluginDemo2{
  
  //参数:flutter_plugin_demo2要与dart定义保持一致
  static const MethodChannel _channel = MethodChannel('flutter_plugin_demo2');

  //参数flutter_show_alert/event要与dart保持一致
  static const EventChannel? _eventChannel = EventChannel("flutter_show_alert/event");

  static EventCallback? callBack;

  StreamSubscription<dynamic>? _streamSubscription;

  // 方法1:初始化构造方法设置监听内容(统一分发)
  FlutterPluginDemo2(){
    init();
  }

   void init(){
    print("FlutterPluginDemo2 init....");
    _streamSubscription =  _eventChannel?.receiveBroadcastStream().listen((event) {
      print("receiveBroadcastStream.....");
      print("receiveBroadcastStream.....event:$event");
      final Map<dynamic,dynamic> map = event;
      String? key = map["key"];
      int? value = map["value"];
      print("handle on ---$key---$value");
      if(map["key"] == "changeVoice"){
        callBack!(key,0);
      }
      else if(map["key"] == "getCount") {
        callBack!(key,value);
      }
      //  Image.memory(bytes)
    },onError: errorEventListen,onDone:doneEventListen,) as StreamSubscription;

    // _channel.setMethodCallHandler(flutterMethod);
  }

  //设置插件方法回调
    void setMethodCallback(Future<dynamic> Function(MethodCall call)? handler){
      _channel.setMethodCallHandler(handler);
   }

  Future<dynamic> flutterMethod(MethodCall methodCall) async{

    print("methodCall: $methodCall.method");
    switch (methodCall.method) {

      case 'test':
        String msg = methodCall.arguments["msg"];
        print("param:"+msg);
        break;

    }

  }

  void test(String param){
    print("接收到了原生端的异步方法=====$param");
  }
  errorEventListen(Object obj) {
    final Object e = obj;
    print("错误打印为------$obj");
    throw e;
  }

  doneEventListen() {
    print("flutter响应完成------");
  }

  static void listener(EventCallback tempCallback) {
    callBack = tempCallback;
  }

  // test(String param){
  //   print("test------$param");
  // }

  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Future<String?> get registerCallBack async {
    print("调用原生的registerCallBack方法");
    final String? originalStr = await _channel.invokeMethod('registerCallBack');
    return originalStr;
  }

  static Future<String?> get originalAllData async {
    print("调用原生的originalAllData方法");
    final String? originalStr = await _channel.invokeMethod('originalAllData');
    return originalStr;
  }

  static Future<String?> sendParamsToOriginal(int key,String value) async {
    Map params = {
      "key":key,
      "value":value,
    };
    final String? count = await _channel.invokeMethod('sendParamsToOriginal',params);
    return count;
  }

  static Future<String?> sendOriginalToHandle(String key,int value) async {
    Map params = {
      "key":key,
      "value":value,
    };
    final String? count = await _channel.invokeMethod('sendOriginalToHandle',params);
    return count;
  }
}


  • Flutter 插件代码:
import 'dart:async';

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

typedef void EventCallback(args,args2);


class FlutterPluginDemo2{

  //参数:flutter_plugin_demo2要与dart定义保持一致
  static const MethodChannel _channel = MethodChannel('flutter_plugin_demo2');

  //参数flutter_show_alert/event要与dart保持一致
  static const EventChannel? _eventChannel = EventChannel("flutter_show_alert/event");

  static EventCallback? callBack;

  StreamSubscription<dynamic>? _streamSubscription;

  // 方法1:初始化构造方法设置监听内容(统一分发)
  FlutterPluginDemo2(){
    init();
  }

   void init(){
    print("FlutterPluginDemo2 init....");
    _streamSubscription =  _eventChannel?.receiveBroadcastStream().listen((event) {
      print("receiveBroadcastStream.....");
      print("receiveBroadcastStream.....event:$event");
      final Map<dynamic,dynamic> map = event;
      String? key = map["key"];
      int? value = map["value"];
      print("handle on ---$key---$value");
      if(map["key"] == "changeVoice"){
        callBack!(key,0);
      }
      else if(map["key"] == "getCount") {
        callBack!(key,value);
      }
      //  Image.memory(bytes)
    },onError: errorEventListen,onDone:doneEventListen,) as StreamSubscription;

    // _channel.setMethodCallHandler(flutterMethod);
  }

  //设置插件方法回调
    void setMethodCallback(Future<dynamic> Function(MethodCall call)? handler){
      _channel.setMethodCallHandler(handler);
   }

  Future<dynamic> flutterMethod(MethodCall methodCall) async{

    print("methodCall: $methodCall.method");
    switch (methodCall.method) {

      case 'test':
        String msg = methodCall.arguments["msg"];
        print("param:"+msg);
        break;

    }

  }

  void test(String param){
    print("接收到了原生端的异步方法=====$param");
  }
  errorEventListen(Object obj) {
    final Object e = obj;
    print("错误打印为------$obj");
    throw e;
  }

  doneEventListen() {
    print("flutter响应完成------");
  }

  static void listener(EventCallback tempCallback) {
    callBack = tempCallback;
  }

  // test(String param){
  //   print("test------$param");
  // }

  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Future<String?> get registerCallBack async {
    print("调用原生的registerCallBack方法");
    final String? originalStr = await _channel.invokeMethod('registerCallBack');
    return originalStr;
  }

  static Future<String?> get originalAllData async {
    print("调用原生的originalAllData方法");
    final String? originalStr = await _channel.invokeMethod('originalAllData');
    return originalStr;
  }

  static Future<String?> sendParamsToOriginal(int key,String value) async {
    Map params = {
      "key":key,
      "value":value,
    };
    final String? count = await _channel.invokeMethod('sendParamsToOriginal',params);
    return count;
  }

  static Future<String?> sendOriginalToHandle(String key,int value) async {
    Map params = {
      "key":key,
      "value":value,
    };
    final String? count = await _channel.invokeMethod('sendOriginalToHandle',params);
    return count;
  }
}

  • Flutter调用代码:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_plugin_demo2/flutter_plugin_demo2.dart';
import 'package:flutter_plugin_demo2_example/more_Params_page.dart';
import 'package:flutter_plugin_demo2_example/show_native_page.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        "/moreParams": (context) => MoreParamsPage(),
      },
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);

  
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Running on: $_platformVersion\n'),
            const Divider(),
            Text(_originalStr + "\n"),
            InkWell(
              onTap: () {

                print("开始flutter调用原生方法");
                updateAndroidInfoData();
              },
              child: Container(
                padding: const EdgeInsets.all(8),
                color: Colors.red,
                child: Text("flutter调用原生~~"),
              ),
            ),
            const Divider(),
            InkWell(
                onTap: () async {
                  print("flutter传值");

                  Navigator.pushNamed(context, "/moreParams");
                },
                child: Container(
                  padding: const EdgeInsets.all(8),
                  color: Colors.red,
                  child: Text("flutter传值~~"),
                )),
            const Divider(),
            InkWell(
                onTap: () async {
                  print("flutter显示原生View");

                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => ShowNativePage()),
                  );
                },
                child: Container(
                  padding: const EdgeInsets.all(8),
                  color: Colors.red,
                  child: Text("flutter显示原生View~~"),
                )),

            const Divider(),
            InkWell(
              onTap:()async{
                 String str = await FlutterPluginDemo2.registerCallBack??"no method";
                 print("success :$str");

              },
              child: Container(
                padding: const EdgeInsets.all(8),
                color: Colors.red,
                child: Text("原生异步定时回调"),
              )
            )

            ,Text('异步回调:'+fromMobileStr)
          ],
        ),
      ),
    );
  }

  String _platformVersion = 'Unknown';
  String _originalStr = "init data";
  String fromMobileStr = "fromMobileStr";

  FlutterPluginDemo2 flutterPluginDemo2 =  FlutterPluginDemo2();

  
  void initState() {
    super.initState();
    initPlatformState();
    flutterPluginDemo2.setMethodCallback(flutterMethod);
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await FlutterPluginDemo2.platformVersion ??'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }


  Future<dynamic> flutterMethod(MethodCall methodCall) async{

    print("methodCall test: $methodCall.method");
    switch (methodCall.method) {

      case 'test':
        String msg = methodCall.arguments["msg"];
        print("param:"+msg);
        setState(() {
          fromMobileStr = msg;
        });
        break;

    }

  }

  Future<void> updateAndroidInfoData() async {
    String originalStr;

    try {
      originalStr =
          await FlutterPluginDemo2.originalAllData ?? "Unknow Not Back";
    } on PlatformException {
      originalStr = "Failed Not Back";
    }
    if (!mounted) return;

    setState(() {
      _originalStr = originalStr;
    });
  }
}

你可能感兴趣的:(flutter,dart,flutter)