Flutter区块链连接插件web3_connect的使用

Flutter区块链连接插件web3_connect的使用

本README描述了该包。如果您将此包发布到pub.dev,则此README的内容会出现在您的包的首页。

功能

通过WalletConnect连接所有可用的钱包,并获取与智能合约交互所需的变量。 (目前测试了Rainbow和MetaMask)。

使用方法

Web3Connect w3c = Web3Connect();
w3c.connect(); // 建立连接并弹出选择钱包的窗口
w3c.disconnect(); // 结束会话
w3c.enterRpcUrl("http://localhost:7545"); // 输入您选择的RPC URL
w3c.account; // 字符串,包含已连接的账户号码
w3c.credentials; // WalletConnectEthereumCredentials,用于与智能合约交互

额外信息

作为更好的钱包集成体验的起点而创建。欢迎在仓库中创建问题以改进此包。


完整示例Demo

main.dart

import 'package:flutter/material.dart';
import 'package:web3_connect/web3_connect.dart';

// 登录页面
class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  [@override](/user/override)
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  Web3Connect connection = Web3Connect();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("登录页面")),
      body: Center(
          child: ElevatedButton(
        child: const Text("登录"),
        onPressed: () async {
          await connection.connect();
          if (connection.account != "") {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: ((context) => Home(connection: connection))));
          }
        },
      )),
    );
  }
}

// 主页
class Home extends StatefulWidget {
  const Home({Key? key, required this.connection}) : super(key: key);
  final Web3Connect connection;

  [@override](/user/override)
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  bool killed = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("主页"),
        automaticallyImplyLeading: false,
      ),
      body: Center(
        child: Column(
          children: [
            const SizedBox(height: 20),
            Text(widget.connection.account),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                await widget.connection.disconnect();
                setState(() {
                  killed = true;
                });
              },
              child: const Text("结束会话"),
            ),
            const SizedBox(height: 20),
            killed
                ? const Text(
                    "会话已结束",
                    style: TextStyle(color: Colors.red),
                  )
                : const Text("会话已连接"),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter区块链连接插件web3_connect的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter区块链连接插件web3_connect的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


web3_connect 是一个用于在 Flutter 应用中连接区块链网络的插件。它允许你与以太坊区块链进行交互,包括连接到钱包、发送交易、调用智能合约等。以下是如何在 Flutter 项目中使用 web3_connect 插件的步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 web3_connect 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  web3_connect: ^0.1.0  # 请检查最新版本

然后运行 flutter pub get 来获取依赖。

2. 初始化 Web3Connect

在你的 Dart 文件中,导入 web3_connect 库并初始化 Web3Connect 实例:

import 'package:web3_connect/web3_connect.dart';

final web3Connect = Web3Connect();

3. 连接到钱包

你可以使用 web3Connect 实例来连接到用户的以太坊钱包。通常,用户可以选择 MetaMask 或其他支持的钱包进行连接。

Future<void> connectWallet() async {
  try {
    final credentials = await web3Connect.connect();
    print('Connected to wallet: ${credentials.address}');
  } catch (e) {
    print('Failed to connect to wallet: $e');
  }
}

4. 获取账户余额

连接到钱包后,你可以获取用户的账户余额:

Future<void> getBalance() async {
  try {
    final credentials = await web3Connect.connect();
    final balance = await web3Connect.getBalance(credentials.address);
    print('Account balance: $balance ETH');
  } catch (e) {
    print('Failed to get balance: $e');
  }
}

5. 发送交易

你可以使用 web3Connect 来发送以太坊交易:

Future<void> sendTransaction() async {
  try {
    final credentials = await web3Connect.connect();
    final receipt = await web3Connect.sendTransaction(
      credentials,
      to: '0xRecipientAddress',
      value: BigInt.from(1000000000000000000), // 1 ETH
    );
    print('Transaction receipt: $receipt');
  } catch (e) {
    print('Failed to send transaction: $e');
  }
}

6. 调用智能合约

你还可以使用 web3Connect 来调用智能合约的函数:

Future<void> callContractFunction() async {
  try {
    final credentials = await web3Connect.connect();
    final contractAddress = '0xContractAddress';
    final abi = '[{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"setValue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]';
    
    final result = await web3Connect.callContractFunction(
      credentials,
      contractAddress,
      abi,
      'setValue',
      [BigInt.from(42)],
    );
    print('Contract function result: $result');
  } catch (e) {
    print('Failed to call contract function: $e');
  }
}

7. 断开连接

当你不再需要与钱包连接时,可以断开连接:

Future<void> disconnectWallet() async {
  await web3Connect.disconnect();
  print('Disconnected from wallet');
}

8. 处理错误

在使用 web3Connect 时,可能会遇到各种错误,例如用户拒绝连接、网络问题等。确保在代码中正确处理这些错误。

try {
  // Your web3Connect code here
} catch (e) {
  print('An error occurred: $e');
}

9. 示例应用

以下是一个简单的 Flutter 应用示例,展示了如何使用 web3Connect 连接到以太坊钱包并获取余额:

import 'package:flutter/material.dart';
import 'package:web3_connect/web3_connect.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Web3ConnectExample(),
    );
  }
}

class Web3ConnectExample extends StatefulWidget {
  [@override](/user/override)
  _Web3ConnectExampleState createState() => _Web3ConnectExampleState();
}

class _Web3ConnectExampleState extends State<Web3ConnectExample> {
  final web3Connect = Web3Connect();
  String _balance = '0 ETH';

  Future<void> _connectWallet() async {
    try {
      final credentials = await web3Connect.connect();
      final balance = await web3Connect.getBalance(credentials.address);
      setState(() {
        _balance = '$balance ETH';
      });
    } catch (e) {
      print('Failed to connect to wallet: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Web3Connect Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Balance: $_balance'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _connectWallet,
              child: Text('Connect Wallet'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部