在看flutter boost源码进程中,看到一个messages.m的文件,在文件的开头有这么一行注释
// Copyright (c) 2019 Alibaba Group. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v3.2.9), do not edit directly.
// See also: https://pub.dev/packages/pigeon
由此看看来这是一个经过pigeon东西主动生成的代码。 因此研究一下pigeon的简略运用进程。
Flutter Pigeon pub.dev/packages/pi… 是一个用于在Dart和原生代码(如Android和iOS)之间进行通讯的库。它通常用于在Flutter应用程序和原生平台之间传递数据和调用办法。
以下是运用Flutter Pigeon的一般流程:
创立插件:
flutter create --template=plugin --platforms=ios,android test_flutter_plugin -i objc -a java
增加pigeo开发包
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
pigeon:
增加源码
跟lib目录同一个级,新建一个pigeo文件夹,这儿面放接口文件,将来pigeo生成东西,就用这些接口文件来生成代码:
文件名为:message.dart
import 'package:pigeon/pigeon.dart';
@HostApi()
abstract class AppNativeApi {
String? getHost();
String? getBrokerId();
}
编写pigeo代码生成脚本
脚本文件名为run_pigeon.sh
flutter pub run pigeon
--input pigeon/message.dart
--dart_out lib/message.dart
--objc_header_out ios/Classes/message.h
--objc_source_out ios/Classes/message.m
--java_out android/src/main/java/com/example/test_flutter_plugin/Message.java
--java_package "io.flutter.plugins"
运行脚本
sh run_pigeon.sh
这样咱们就经过一个接口文件,生成了代码:
初始化代码
这儿咱们在插件中初始化
#import "message.h"
@interface TestFlutterPlugin () <AppNativeApi>
@end
@implementation TestFlutterPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FlutterMethodChannel *channel = [FlutterMethodChannel
methodChannelWithName:@"test_flutter_plugin"
binaryMessenger:[registrar messenger]];
TestFlutterPlugin *instance = [[TestFlutterPlugin alloc] init];
[registrar addMethodCallDelegate:instance channel:channel];
AppNativeApiSetup([registrar messenger], instance);
}
- (nullable NSString *)getBrokerIdWithError:(FlutterError * _Nullable __autoreleasing * _Nonnull)error {
return @"123";
}
- (nullable NSString *)getHostWithError:(FlutterError * _Nullable __autoreleasing * _Nonnull)error {
return @"10.253.22.122";
}
@end
运用代码
import 'package:flutter/material.dart';
import 'package:test_flutter_plugin/message.dart';
class TestPigeon extends StatefulWidget {
const TestPigeon({super.key});
@override
State<TestPigeon> createState() => _TestPigeonState();
}
class _TestPigeonState extends State<TestPigeon> {
String? host;
String? brokerId;
@override
void initState() {
super.initState();
loadData();
}
Future<void> loadData() async {
brokerId = await AppNativeApi().getBrokerId();
setState(() {});
host = await AppNativeApi().getHost();
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
Text('$brokerId'),
Text('$host'),
],
),
);
}
}
总结
本文经过运用 pigeon,编写一个简略的dart完成的接口文件,就可以主动生成native 和 flutter之间通讯的一个通道。
经过在flutter端调用通道的api(pigeon主动生成的),就可以获取native端的数据。