您好,欢迎来到微智科技网。
搜索
您的当前位置:首页Flutter Plugin简单开发

Flutter Plugin简单开发

来源:微智科技网

新建项目

项目结构

flutter_plugin_platform_interface.dart文件就是我们定义接口的地方,flutter_plugin_method_channel.dart是对应AndoidIOS的文件,flutter_plugin_web.dart是对应web平台。

方法实现

AndroidIOS平台要分别实现flutter_plugin_platform_interface.dart定义的方法。这里以AndroidWeb为例,实现接口中的方法。

Android端

2、打开后的界面如下

我们主要在FlutterPlugin这个文件的onMethodCall方法中做具体实现

无参方法的调用

1、在flutter_plugin_platform_interface.dart类中增加方法

Future<String?> hello(){
   
  throw UnimplementedError('hello() has not been implemented.');
}

2、在flutter_plugin_method_channel.dart类中实现上面的方法


Future<String?> hello() async {
   
  final msg = await methodChannel.invokeMethod<String>('hello');
  return msg;
}

3、在flutter_plugin.dart中调用

Future<String?> hello() {
   
  return FlutterPluginPlatform.instance.hello();
}

4、Android端实现

FlutterPlugin.kt

override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
   
  when (call.method) {
   
    "getPlatformVersion" -> {
   
      result.success("Android ${
     android.os.Build.VERSION.RELEASE}")
    }
    "hello" -> {
   
      result.success("Android invoke==>hello()")
    }
    else -> {
   
      result.notImplemented()
    }
  }
}

5、在Example中测试

main.dart

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';

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

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

class MyApp extends StatefulWidget {
   
  const MyApp({
   super.key});

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

class _MyAppState extends State<MyApp> {
   
  String _platformVersion = 'Unknown';
  String? _msg;
  final _flutterPlugin = FlutterPlugin();

  
  void initState() {
   
    super.initState();
    initPlatformState();
  }

  // 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 _flutterPlugin.getPlatformVersion() ?? '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;
    });
  }

  
  Widget build(BuildContext context) {
   
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('Running on: $_platformVersion\n'),
              Text('msg: ${
     _msg ?? ""}\n'),
              ElevatedButton(
                onPressed: () async {
   
                  var msg = await _flutterPlugin.hello();
                  if (kDebugMode) {
   
                    print('msg from android:$msg');
                    setState(() {
   
                      _msg = msg;
                    });
                  }
                },
                child: const Text("调用hello")),
            ],
          ),
        ),
      ),
    );
  }
}

6、测试结果

可以看出,成功调用到了Android端的方法

有参方法的调用

1、在flutter_plugin_platform_interface.dart类中增加方法

Future<String?> hi(String message){
   
  throw UnimplementedError('hi() has not been implemented.');
}

2、在flutter_plugin_method_channel.dart类中实现上面的方法


Future<String?> hi(String message) async {
   
  Map<String, dynamic> param = <String, dynamic>{
   };
  param["message"] = message;
  final msg = await methodChannel.invokeMethod<String>('hi', param);
  return msg;
}

3、在flutter_plugin.dart中调用

Future<String?> hi(String message) {
   
  return FlutterPluginPlatform.instance.hi(message);
}

4、Android端实现

FlutterPlugin.kt

override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
   
  when (call.method) {
   
    "getPlatformVersion" -> {
   
      result.success("Android ${
     android.os.Build.VERSION.RELEASE}")
    }
    "hello" -> 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 7swz.com 版权所有 赣ICP备2024042798号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务