Flutter钱包核心功能绑定插件wallet_core_bindings的使用
Flutter钱包核心功能绑定插件wallet_core_bindings的使用
wallet_core_bindings
Dart绑定用于在Flutter和Dart中使用的Trust Wallet Core。
包
Package | Pub |
---|---|
wallet_core_bindings | |
wallet_core_bindings_native | |
wallet_core_bindings_wasm | |
wallet_core_bindings_libs | |
wallet_core_bindings_wasm_assets |
特性
- 包含TrustWalletCore的文件和Protobuf文件绑定。
- 提供原生和WebAssembly系统接口,支持所有平台。
- 将API重新打包以便于使用。
- 结合Dart垃圾回收机制,无需手动管理内存。
- 同步更新TrustWalletCore版本,并保持API一致。
入门
可以使用两种方式来使用wallet_core_bindings,分别是原生(Native)和WebAssembly。请根据以下说明选择适合的方式。
平台支持
平台 | 原生(Native) | WebAssembly | wallet_core_bindings_libs |
---|---|---|---|
Android | ✔️ | ✔️ | ✔️ |
iOS | ✔️ | ✔️ | ✔️ |
macOS | ✔️ | ✔️ | ✔️ |
Linux | ✔️ | ✔️ | ✔️ |
Windows | ❌ | ✔️ | ❌ |
Web | ❌ | ✔️ | ❌ |
原生
原生功能依赖于由Trust Wallet Core编译的动态库,并通过dart:ffi进行绑定。
wallet_core_bindings_libs
包含原生动态库。目前仅支持Android和iOS。由于CPU架构的多样性,Linux和macOS可以通过自行编译并添加到项目中。后续版本可能会找到合适的方法来支持它们。当前不支持Windows。- 更多信息参见wallet_core_bindings_libs。
dependencies:
wallet_core_bindings: version
wallet_core_bindings_native: version
wallet_core_bindings_libs: version
import 'package:wallet_core_bindings/wallet_core_bindings.dart';
import 'package:wallet_core_bindings_native/wallet_core_bindings_native.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await WalletCoreBindingsNativeImpl().initialize();
runApp(const MyApp());
}
WebAssembly
构建WalletCore用于WASM,通过WASI和wasm_run进行绑定。
- 它适用于不支持原生功能的平台,如Web和Windows。然而,WASM本身具有强大的跨平台特性,并不限于这两个平台。
dependencies:
wasm_run_flutter: version
wallet_core_bindings: version
wallet_core_bindings_wasm: version
wallet_core_bindings_wasm_assets: version
import 'package:wallet_core_bindings/wallet_core_bindings.dart';
import 'package:wallet_core_bindings_wasm/wallet_core_bindings_wasm.dart';
import 'package:wasm_run_flutter/wasm_run_flutter.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await WasmRunLibrary.setUp(override: false);
await WalletCoreBindingsWasmImpl().initialize();
runApp(const MyApp());
}
使用
生成
Protobuf
参考TrustWalletCore构建文档,完成生成文件的步骤。从src/proto目录中提取proto文件,并使用protoc_plugin将它们编译为Dart代码。
cd ../proto/TrustWalletCore/
protoc --dart_out=../../wallet_core_bindings/lib/proto/ ./*
许可证
商业许可证
如果您想在商业应用、网站或插件中使用wallet_core_bindings,需要从作者处获得商业许可证。请与xuelongqy@qq.com联系以获取更多信息。一旦获得许可证,您的授权信息将出现在AUTHORIZED.md中。
开源许可证
以下是完整的示例代码:
import 'package:flutter/material.dart';
import 'package:wallet_core_bindings/wallet_core_bindings.dart';
import 'package:wallet_core_bindings_native/wallet_core_bindings_native.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 使用原生
await WalletCoreBindingsNativeImpl().initialize();
// 使用WebAssembly
// await WasmRunLibrary.setUp(override: false);
// await WalletCoreBindingsWasmImpl().initialize();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
TWAnyAddress.isValid(
'0x4E5B2e1dc63F6b91cb6Cd759936495434C7e972F', TWCoinType.Ethereum);
final privateKey = TWPrivateKey();
print(privateKey.data.toString());
setState(() {
_counter++;
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
更多关于Flutter钱包核心功能绑定插件wallet_core_bindings的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter钱包核心功能绑定插件wallet_core_bindings的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中绑定和使用一个名为 wallet_core_bindings
的插件(假设该插件已经存在并且已经用C/C++实现了钱包的核心功能)的示例。这涉及到几个关键步骤:
-
创建Flutter插件项目(如果还没有的话): 假设你已经有一个Flutter项目,如果没有,可以使用以下命令创建一个新的Flutter项目:
flutter create my_wallet_app cd my_wallet_app
-
添加原生插件支持: 你需要为iOS和Android平台分别添加对
wallet_core_bindings
的支持。对于iOS:
- 在
ios/
目录下创建一个新的Flutter插件项目,例如wallet_core_bindings
。 - 在
ios/wallet_core_bindings/Classes
目录下创建WalletCoreBindingsPlugin.swift
或WalletCoreBindingsPlugin.m
文件。 - 编写Objective-C/Swift代码来桥接C/C++钱包核心库。
示例
WalletCoreBindingsPlugin.swift
:import Flutter import wallet_core // 假设这是你的C/C++库 public class WalletCoreBindingsPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "my_wallet_core_bindings", binaryMessenger: registrar.messenger()) let instance = WalletCoreBindingsPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "generateWallet": let wallet = WalletCore.generateWallet() // 假设这是生成钱包的函数 result(wallet.toJSON()) // 假设wallet有toJSON方法返回JSON表示 default: result(FlutterMethodNotImplemented) } } }
对于Android:
- 在
android/
目录下创建一个新的Flutter插件项目,例如wallet_core_bindings
。 - 在
android/src/main/java/com/example/wallet_core_bindings
目录下创建WalletCoreBindingsPlugin.java
文件。 - 编写Java代码来桥接C/C++钱包核心库(通常通过JNI)。
示例
WalletCoreBindingsPlugin.java
:package com.example.wallet_core_bindings; import androidx.annotation.NonNull; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; 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 WalletCoreBindingsPlugin implements FlutterPlugin, ActivityAware, MethodCallHandler { private MethodChannel channel; private ActivityPluginBinding activityBinding; @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { BinaryMessenger messenger = flutterPluginBinding.getBinaryMessenger(); channel = new MethodChannel(messenger, "my_wallet_core_bindings"); channel.setMethodCallHandler(this); } @Override public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) { if (call.method.equals("generateWallet")) { String walletJson = WalletCore.generateWallet(); // 假设这是生成钱包并返回JSON字符串的静态方法 result.success(walletJson); } else { result.notImplemented(); } } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { channel.setMethodCallHandler(null); } @Override public void onAttachedToActivity(ActivityPluginBinding binding) { activityBinding = binding; } @Override public void onDetachedFromActivityForConfigChanges() { activityBinding = null; } @Override public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) { activityBinding = binding; } @Override public void onDetachedFromActivity() { activityBinding = null; } }
- 在
-
在Flutter项目中引用插件:
- 在
pubspec.yaml
文件中添加对本地插件的依赖:dependencies: flutter: sdk: flutter wallet_core_bindings: path: ../path_to_your_local_plugin
- 在
-
在Flutter中使用插件:
- 在你的Dart代码中,你可以通过平台通道与插件交互。
示例
main.dart
:import 'package:flutter/material.dart'; import 'package:wallet_core_bindings/wallet_core_bindings.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Wallet App'), ), body: Center( child: ElevatedButton( onPressed: () async { try { final walletJson = await WalletCoreBindings.generateWallet(); print("Generated Wallet: $walletJson"); } catch (e) { print("Error: $e"); } }, child: Text('Generate Wallet'), ), ), ), ); } }
- 你需要创建一个
wallet_core_bindings.dart
文件来定义平台通道的方法:
示例
wallet_core_bindings.dart
:import 'dart:async'; const MethodChannel _channel = MethodChannel('my_wallet_core_bindings'); class WalletCoreBindings { static Future<String> generateWallet() async { final String walletJson = await _channel.invokeMethod('generateWallet'); return walletJson; } }
请注意,上述代码只是一个示例,具体实现细节可能会因你的C/C++钱包核心库的实现以及Flutter插件的开发需求而有所不同。你需要根据实际情况调整代码。