Flutter区块链交互插件web3dart_plus的使用
Flutter区块链交互插件web3dart_plus的使用
在Flutter中与以太坊区块链进行交互时,web3dart_plus
是一个非常有用的插件。它允许开发者通过RPC连接到以太坊节点,并执行各种操作,例如发送交易、调用智能合约等。
特性
- 连接到以太坊节点:通过RPC API调用常用方法。
- 发送签名的以太坊交易。
- 生成私钥并设置新的以太坊地址。
- 调用智能合约函数并监听合约事件。
- 基于智能合约ABI生成代码,简化交互过程。
待办事项
- 支持编码所有Solidity支持的数据类型,但目前未完全支持
(u)fixed
类型(这些类型不常用)。
使用方法
凭据和钱包
为了在以太坊网络上发送交易,需要一些凭据。web3dart_plus
支持从私钥或v3钱包文件创建凭据。
从私钥创建凭据
import 'package:web3dart_plus/web3dart.dart';
const privateKey = 'a2fd51b96dc55aeb14b30d55a6b3121c7b9c599500c1beb92a389c3377adc86e';
void main() async {
final credentials = EthPrivateKey.fromHex(privateKey);
// 提取公钥和地址
final address = await credentials.extractAddress();
print(address.hexEip55); // 打印地址
}
随机生成新私钥
import 'dart:math';
import 'package:web3dart_plus/web3dart.dart';
void main() async {
final rng = Random.secure(); // 创建随机数生成器
final credentials = EthPrivateKey.createRandom(rng);
final address = await credentials.extractAddress();
print(address.hexEip55);
}
连接到RPC服务器
web3dart_plus
不会直接将签名的交易发送给矿工,而是依赖于RPC客户端完成此操作。可以使用 Infura 的公共RPC API,或者搭建自己的节点(例如使用 Geth)。如果只是测试,可以使用 Truffle 和 Ganache 提供的私有测试网。
import 'package:http/http.dart' as http;
import 'package:web3dart_plus/web3dart.dart';
const rpcUrl = 'http://localhost:7545';
void main() async {
final httpClient = http.Client();
final client = Web3Client(rpcUrl, httpClient);
// 获取账户余额
final address = EthereumAddress.fromHex('0x...'); // 替换为实际地址
final balance = await client.getBalance(address);
print(balance.getInWei); // 打印以太币数量(单位为wei)
}
发送交易
可以使用 Web3Client
创建、签署并发送以太坊交易。
import 'package:web3dart_plus/web3dart.dart';
import 'package:http/http.dart' as http;
const rpcUrl = 'http://localhost:7545';
const privateKey = 'a2fd51b96dc55aeb14b30d55a6b3121c7b9c599500c1beb92a389c3377adc86e';
void main() async {
final httpClient = http.Client();
final client = Web3Client(rpcUrl, httpClient);
final credentials = EthPrivateKey.fromHex(privateKey);
// 发送交易
await client.sendTransaction(
credentials,
Transaction(
to: EthereumAddress.fromHex('0xC914Bb2ba888e3367bcecEb5C2d99DF7C7423706'),
gasPrice: EtherAmount.inWei(BigInt.one),
maxGas: 100000,
value: EtherAmount.fromUnitAndValue(EtherUnit.ether, 1),
),
);
await client.dispose(); // 关闭客户端
}
智能合约
web3dart_plus
可以解析智能合约的ABI并与其交互,包括调用函数和监听事件。
import 'package:web3dart_plus/web3dart.dart';
import 'package:http/http.dart' as http;
const rpcUrl = 'http://localhost:7545';
const privateKey = 'a2fd51b96dc55aeb14b30d55a6b3121c7b9c599500c1beb92a389c3377adc86e';
void main() async {
final httpClient = http.Client();
final client = Web3Client(rpcUrl, httpClient);
final credentials = EthPrivateKey.fromHex(privateKey);
// 调用智能合约函数
final contractAddress = EthereumAddress.fromHex('0x...');
final contract = DeployedContract(
ContractAbi.fromJson(jsonString, 'contractName'),
contractAddress,
);
final result = await client.call(
contract: contract,
function: contract.function('functionName'),
params: [],
);
print(result); // 打印返回值
}
自动生成Dart代码
通过Dart构建系统,web3dart_plus
可以根据智能合约的ABI自动生成Dart代码,方便与合约交互。
- 在
lib/
目录下添加.abi.json
文件。 - 添加
build_runner
依赖并运行以下命令:pub run build_runner build
- 生成的
.g.dart
文件包含与合约交互的代码。
示例代码
以下是一个完整的示例代码,展示如何使用 web3dart_plus
进行基本的区块链操作:
import 'package:http/http.dart';
import 'package:web3dart_plus/web3dart.dart';
const String privateKey =
'a2fd51b96dc55aeb14b30d55a6b3121c7b9c599500c1beb92a389c3377adc86e';
const String rpcUrl = 'http://localhost:7545';
Future<void> main() async {
final client = Web3Client(rpcUrl, Client());
final credentials = EthPrivateKey.fromHex(privateKey);
final address = credentials.address;
print(address.hexEip55);
print(await client.getBalance(address));
await client.sendTransaction(
credentials,
Transaction(
to: EthereumAddress.fromHex('0xC914Bb2ba888e3367bcecEb5C2d99DF7C7423706'),
gasPrice: EtherAmount.inWei(BigInt.one),
maxGas: 100000,
value: EtherAmount.fromUnitAndValue(EtherUnit.ether, 1),
),
);
await client.dispose();
}
更多关于Flutter区块链交互插件web3dart_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
web3dart_plus
是一个基于 web3dart
的 Flutter 插件,用于与以太坊区块链进行交互。它提供了更多的功能和改进,使得在 Flutter 应用中与智能合约交互更加方便。以下是 web3dart_plus
的基本使用方法:
1. 添加依赖
首先,在你的 pubspec.yaml
文件中添加 web3dart_plus
依赖:
dependencies:
flutter:
sdk: flutter
web3dart_plus: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来安装依赖。
2. 导入包
在你的 Dart 文件中导入 web3dart_plus
:
import 'package:web3dart_plus/web3dart_plus.dart';
3. 连接到以太坊节点
你需要连接到一个以太坊节点,可以使用 Infura 或者本地节点。以下是使用 Infura 的示例:
final client = Web3Client(
'https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID',
http.Client(),
);
4. 获取账户余额
你可以使用 getBalance
方法来获取某个以太坊地址的余额:
final address = EthereumAddress.fromHex('0xYourEthereumAddress');
final balance = await client.getBalance(address);
print('Balance: ${balance.getValueInUnit(EtherUnit.ether)} ETH');
5. 与智能合约交互
要与智能合约交互,首先需要定义合约的 ABI 和地址。假设你有一个简单的合约:
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 public data;
function set(uint256 _data) public {
data = _data;
}
function get() public view returns (uint256) {
return data;
}
}
你可以使用 DeployedContract
和 ContractFunction
来与合约交互:
final contractAddress = EthereumAddress.fromHex('0xYourContractAddress');
final contractAbi = ContractAbi.fromJson('[YOUR_CONTRACT_ABI_JSON]', 'SimpleStorage');
final contract = DeployedContract(contractAbi, contractAddress);
// 调用合约的 get 方法
final getFunction = contract.function('get');
final result = await client.call(contract: contract, function: getFunction, params: []);
print('Data: ${result[0]}');
// 调用合约的 set 方法
final credentials = EthPrivateKey.fromHex('YOUR_PRIVATE_KEY');
final setFunction = contract.function('set');
final transaction = Transaction.callContract(
contract: contract,
function: setFunction,
parameters: [BigInt.from(42)],
maxGas: 100000,
);
final txHash = await client.sendTransaction(credentials, transaction);
print('Transaction Hash: $txHash');
6. 监听事件
你可以使用 EventFilter
来监听合约事件:
final event = contract.event('DataChanged');
final filter = EventFilter(
event: event,
fromBlock: BlockNum.current(),
toBlock: BlockNum.current(),
);
final events = await client.getLogs(filter);
for (var event in events) {
print('Event: ${event.data}');
}
7. 断开连接
当你不再需要与以太坊节点交互时,可以断开连接:
client.dispose();