Flutter用户通道通信插件flutter_user_channel的使用
Flutter用户通道通信插件flutter_user_channel的使用
该插件主要用于Flutter与原生应用(Android和iOS)混合开发时(通常配合flutter_boost
一起使用),在原生应用中更新Flutter中的用户令牌和其他信息。
开始使用
在Flutter中使用
首先,需要导入插件并监听原生传递过来的信息:
import 'package:flutter_user_channel/flutter_user_channel.dart';
void main() {
/// 监听原生传递过来的token
FlutterUserChannel.listenUserToken(
(p0) {
var completer = Completer();
print("============ 接收到的user token $p0");
// 这里写数据的处理
if (p0 == null) {
completer.complete("========== 接收到user token 为空,已经退出登录");
} else {
completer.complete("========== 接收到user token $p0");
}
return completer.future;
},
);
/// 监听原生传递过来的其它信息
FlutterUserChannel.listenOtherInfo(
(p0) {
var completer = Completer();
print("============ 接收到的数据 $p0");
// 这里写数据的处理
completer.complete("========== 已经接收到数据 $p0");
return completer.future;
},
);
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
final _flutterUserChannelPlugin = FlutterUserChannel();
@override
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 _flutterUserChannelPlugin.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;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Text('Running on: $_platformVersion\n'),
),
),
);
}
}
在iOS中使用
在iOS中,我们需要配置FlutterEngine
并调用相关的方法来更新用户令牌和传递其他信息:
import flutter_boost
import flutter_user_channel
class AppDelegate: UIResponder, UIApplicationDelegate {
// 创建代理,做初始化操作
var flutterBoostDelegate = GMFlutterBoostDelegate()
var flutterEngine: FlutterEngine?
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// ...
// 配置Flutter
configFlutterBoost(application)
// 向flutter同步token
let token = "token"
updateUserTokenInFlutter(token)
return true
}
}
extension AppDelegate {
/// 设置flutter
func configFlutterBoost(_ application: UIApplication) {
let boostDelegate = GMFlutterBoostDelegate()
flutterBoostDelegate = boostDelegate
FlutterBoost.instance().setup(application, delegate: flutterBoostDelegate) {[weak self] engine in
self?.flutterEngine = engine
}
}
}
extension AppDelegate {
/// 更新flutter中的token
func updateUserTokenInFlutter(_ token: String?) {
guard let flutterEngine = flutterEngine else { return }
FlutterUserChannel.updateUserToken(with: token, engine: flutterEngine) {[weak self] result in
print("============updateUserToken \(String(describing: result))")
}
}
/// 传递数据到flutter
func transmitOtherInfoToFlutter(_ value: [String : Any]) {
guard let flutterEngine = flutterEngine else { return }
FlutterUserChannel.transmitOtherInfo(with: value, engine: flutterEngine) { result in
print("============transmitOtherInfo \(String(describing: result))")
}
}
}
在Android中使用
在Android中,使用的类和方法与iOS相同。我们可以通过调用updateUserToken
和transmitOtherInfo
方法来更新用户令牌和传递其他信息:
// 由于示例代码中没有提供具体的Android代码实现,这里仅展示方法签名。
// 实际使用时可以参照iOS代码进行相应的实现。
更多关于Flutter用户通道通信插件flutter_user_channel的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter用户通道通信插件flutter_user_channel的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
flutter_user_channel
是一个用于 Flutter 与原生平台(Android 和 iOS)之间进行通信的插件。通过这个插件,你可以轻松地在 Flutter 和原生代码之间传递数据和方法调用。这种通信通常用于调用原生功能、访问设备硬件或执行一些 Flutter 无法直接完成的任务。
安装插件
首先,你需要在 pubspec.yaml
文件中添加 flutter_user_channel
插件的依赖:
dependencies:
flutter:
sdk: flutter
flutter_user_channel: ^最新版本
然后运行 flutter pub get
来安装插件。
基本用法
1. 在 Flutter 中调用原生方法
在 Flutter 中,你可以使用 FlutterUserChannel
来调用原生平台上的方法。首先,你需要在 Flutter 中创建一个 FlutterUserChannel
实例:
import 'package:flutter_user_channel/flutter_user_channel.dart';
final userChannel = FlutterUserChannel('com.example.my_app/channel_name');
然后,你可以使用 invokeMethod
来调用原生方法:
Future<void> callNativeMethod() async {
try {
final result = await userChannel.invokeMethod('nativeMethodName', {'key': 'value'});
print('Native method result: $result');
} catch (e) {
print('Failed to call native method: $e');
}
}
2. 在原生端实现方法
在 Android 和 iOS 上,你需要为 flutter_user_channel
配置相应的原生代码。
Android
在 Android 项目中,你需要在 MainActivity
中注册 MethodChannel
并处理 Flutter 调用的方法:
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "com.example.my_app/channel_name";
@Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler((call, result) -> {
if (call.method.equals("nativeMethodName")) {
// 处理 Flutter 调用的方法
String value = call.argument("key");
result.success("Response from Android: " + value);
} else {
result.notImplemented();
}
});
}
}
iOS
在 iOS 项目中,你需要在 AppDelegate.swift
中注册 MethodChannel
并处理 Flutter 调用的方法:
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel(name: "com.example.my_app/channel_name",
binaryMessenger: controller.binaryMessenger)
channel.setMethodCallHandler({
(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
if call.method == "nativeMethodName" {
// 处理 Flutter 调用的方法
let value = call.arguments as? [String: Any]
let response = "Response from iOS: \(value?["key"] ?? "")"
result(response)
} else {
result(FlutterMethodNotImplemented)
}
})
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
3. 在原生端调用 Flutter 方法
你也可以在原生端调用 Flutter 中的方法。首先,在 Flutter 中注册一个方法处理程序:
userChannel.setMethodCallHandler((call) async {
if (call.method == 'flutterMethodName') {
return 'Response from Flutter';
}
throw MissingPluginException();
});
然后,在原生端调用这个方法:
Android
MethodChannel channel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL);
channel.invokeMethod("flutterMethodName", null, new MethodChannel.Result() {
@Override
public void success(Object result) {
Log.d("Native", "Flutter method result: " + result);
}
@Override
public void error(String errorCode, String errorMessage, Object errorDetails) {
Log.e("Native", "Error calling Flutter method: " + errorMessage);
}
@Override
public void notImplemented() {
Log.e("Native", "Flutter method not implemented");
}
});
iOS
channel.invokeMethod("flutterMethodName", arguments: nil) { (response) in
print("Flutter method result: \(response ?? "No response")")
}