Flutter区块链交互插件web3_cloud_sdk的使用
Flutter区块链交互插件web3_cloud_sdk的使用
在本教程中,我们将介绍如何使用 web3_cloud_sdk
插件与区块链进行交互。该插件提供了生成助记词、导入导出助记词、创建钱包、获取余额、签名交易以及发送交易等功能。
使用步骤
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 web3_cloud_sdk
和 flutter_dotenv
依赖:
dependencies:
web3_cloud_sdk: ^版本号
flutter_dotenv: ^版本号
然后运行 flutter pub get
安装依赖。
2. 初始化项目
确保你的项目已经正确配置了 .env
文件来存储环境变量(如私钥、RPC URL等)。以下是一个示例 .env
文件:
MNEMONIC=your_mnemonic_phrase
ETH_RPC_URL_GOERLI=https://goerli.infura.io/v3/your_project_id
TO_ADDRESS=接收地址
3. 创建主应用
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:loggy/loggy.dart';
import 'package:web3_cloud_sdk/client_sdk.dart' as clientsdk;
import 'package:web3_cloud_sdk/ethereum_lib.dart' as ethereum;
void main() {
dotenv.load(fileName: '.env'); // 加载环境变量
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Web3 Sample',
theme: ThemeData(primarySwatch: Colors.blue),
home: const MyHomePage(title: 'Flutter Web3 Sample'),
);
}
}
4. 实现功能
4.1 生成助记词
void _generateMnemonic() async {
try {
await clientsdk.generateMnemonic('user@example.com', 256); // 生成24个单词的助记词
_show('Mnemonic generated successfully!');
} catch (e) {
final errorString = clientsdk.GincoSdkError.byErrorCode(e.toString());
logger.error(errorString);
_show(errorString);
}
}
4.2 获取助记词
void _getMnemonic() async {
try {
final mnemonic = await clientsdk.getMnemonic('user@example.com');
logger.info(mnemonic);
_show(mnemonic);
} catch (e) {
final errorString = clientsdk.GincoSdkError.byErrorCode(e.toString());
logger.error(errorString);
_show(errorString);
}
}
4.3 导入助记词
void _importMnemonic() async {
try {
await clientsdk.importMnemonic('user@example.com', dotenv.env['MNEMONIC']!);
_show('Mnemonic imported successfully!');
} catch (e) {
final errorString = clientsdk.GincoSdkError.byErrorCode(e.toString());
logger.error(errorString);
_show(errorString);
}
}
4.4 销毁助记词
void _destroyMnemonic() async {
try {
await clientsdk.destroyMnemonic('user@example.com');
_show('Mnemonic destroyed successfully!');
} catch (e) {
final errorString = clientsdk.GincoSdkError.byErrorCode(e.toString());
logger.error(errorString);
_show(errorString);
}
}
4.5 创建钱包
void _getWallet() async {
try {
final networkParam = ethereum.NetworkParam(
clientsdk.ChainId.ethereumGoerli,
clientsdk.NetworkId.ethereumGoerli,
dotenv.env['ETH_RPC_URL_GOERLI']!,
);
sdk = clientsdk.SdkBase();
wallet = await sdk.evm.createWallet('user@example.com', networkParam);
_show('Wallet created successfully!');
} catch (e) {
final errorString = clientsdk.GincoSdkError.byErrorCode(e.toString());
logger.error(errorString);
_show(errorString);
}
}
4.6 获取账户余额
void _walletBalance() async {
if (wallet == null) {
_show('Wallet does not exist!');
return;
}
try {
final balance = await wallet!.account(0).balance();
logger.info(balance);
_show(ethereum.weiToEther(balance)); // 转换为以太币单位
} catch (e) {
final errorString = clientsdk.GincoSdkError.byErrorCode(e.toString());
logger.error(errorString);
_show(errorString);
}
}
4.7 签名并发送交易
void _signTx() async {
if (wallet == null) {
_show('Wallet does not exist!');
return;
}
try {
signedTx = await ethereum.TxBuilder()
.value(ethereum.etherToWei('0.0001')) // 发送0.0001 ETH
.gasPrice('80000000000') // 设置Gas价格为80 Gwei
.gasLimit(21000)
.to(dotenv.env['TO_ADDRESS']!)
.chainId(clientsdk.ChainId.ethereumGoerli)
.sign(wallet!.account(0))
.build();
logger.info(signedTx);
_show(signedTx!);
} catch (e) {
final errorString = clientsdk.GincoSdkError.byErrorCode(e.toString());
logger.error(errorString);
_show(errorString);
}
}
void _sendTx() async {
if (wallet == null || signedTx == null) {
_show('Signed transaction does not exist!');
return;
}
try {
final txHash = await wallet!.web3.sendTransaction(signedTx!);
logger.info(txHash);
_show(txHash);
} catch (e) {
final errorString = clientsdk.GincoSdkError.byErrorCode(e.toString());
logger.error(errorString);
_show(errorString);
}
}
5. UI界面
[@override](/user/override)
Widget build(BuildContext context) {
Loggy.initLoggy();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Colors.blue)),
onPressed: _generateMnemonic,
child: const Text('Generate Mnemonic'),
),
TextButton(
style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Colors.blue)),
onPressed: _getMnemonic,
child: const Text('Get Mnemonic'),
),
TextButton(
style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Colors.blue)),
onPressed: _importMnemonic,
child: const Text('Import Mnemonic'),
),
TextButton(
style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Colors.blue)),
onPressed: _destroyMnemonic,
child: const Text('Destroy Mnemonic'),
),
TextButton(
style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Colors.blue)),
onPressed: _getWallet,
child: const Text('Create Wallet'),
),
TextButton(
style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Colors.blue)),
onPressed: _getPrivateKey,
child: const Text('Wallet Private Key (for MetaMask)'),
),
TextButton(
style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Colors.blue)),
onPressed: _walletAddress,
child: const Text('Wallet Address'),
),
TextButton(
style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Colors.blue)),
onPressed: _walletBalance,
child: const Text('Wallet Balance'),
),
TextButton(
style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Colors.blue)),
onPressed: _signTx,
child: const Text('Sign Tx'),
),
TextButton(
style: ButtonStyle(foregroundColor: MaterialStateProperty.all(Colors.blue)),
onPressed: _sendTx,
child: const Text('Send Tx'),
),
],
),
),
);
}
更多关于Flutter区块链交互插件web3_cloud_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
web3_cloud_sdk
是一个用于 Flutter 应用与区块链进行交互的插件。它简化了与以太坊区块链的交互过程,允许开发者轻松地发送交易、调用智能合约、查询区块链数据等。以下是使用 web3_cloud_sdk
的基本步骤和示例。
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 web3_cloud_sdk
依赖。
dependencies:
flutter:
sdk: flutter
web3_cloud_sdk: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来获取依赖。
2. 初始化 SDK
在使用 web3_cloud_sdk
之前,你需要初始化 SDK。通常,你需要提供以太坊节点的 RPC URL。
import 'package:web3_cloud_sdk/web3_cloud_sdk.dart';
void main() {
Web3CloudSdk.initialize('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');
}
3. 获取钱包余额
你可以使用 web3_cloud_sdk
来查询某个以太坊地址的余额。
void getBalance() async {
String address = '0xYourEthereumAddress';
BigInt balance = await Web3CloudSdk.instance.getBalance(address);
print('Balance: $balance Wei');
}
4. 发送以太币
你可以使用 web3_cloud_sdk
发送以太币到另一个地址。
void sendEther() async {
String privateKey = 'YourPrivateKey';
String toAddress = '0xRecipientAddress';
BigInt amount = BigInt.from(1000000000000000000); // 1 Ether
String txHash = await Web3CloudSdk.instance.sendEther(
privateKey: privateKey,
toAddress: toAddress,
amount: amount,
);
print('Transaction Hash: $txHash');
}
5. 与智能合约交互
你可以使用 web3_cloud_sdk
与智能合约进行交互。首先,你需要智能合约的 ABI 和地址。
void callContract() async {
String contractAddress = '0xYourContractAddress';
String abi = '[{"constant":true,"inputs":[],"name":"getValue","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]';
String result = await Web3CloudSdk.instance.callContract(
contractAddress: contractAddress,
abi: abi,
functionName: 'getValue',
params: [],
);
print('Contract Call Result: $result');
}
6. 发送智能合约交易
你还可以发送交易来调用智能合约的写入方法。
void sendContractTransaction() async {
String privateKey = 'YourPrivateKey';
String contractAddress = '0xYourContractAddress';
String abi = '[{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"setValue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]';
String txHash = await Web3CloudSdk.instance.sendContractTransaction(
privateKey: privateKey,
contractAddress: contractAddress,
abi: abi,
functionName: 'setValue',
params: [BigInt.from(123)],
);
print('Transaction Hash: $txHash');
}
7. 处理错误
在使用 web3_cloud_sdk
时,可能会遇到各种错误,例如网络问题、交易失败等。你可以使用 try-catch
来捕获并处理这些错误。
void sendEtherSafely() async {
try {
String privateKey = 'YourPrivateKey';
String toAddress = '0xRecipientAddress';
BigInt amount = BigInt.from(1000000000000000000); // 1 Ether
String txHash = await Web3CloudSdk.instance.sendEther(
privateKey: privateKey,
toAddress: toAddress,
amount: amount,
);
print('Transaction Hash: $txHash');
} catch (e) {
print('Error: $e');
}
}