You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已通过flutter_web3连接MetaMask,如何向其发送交易?

实现MetaMask交易发送功能

在你现有的MetaMaskProvider类中添加交易发送逻辑即可,以下是具体实现步骤:

1. 添加交易发送方法

在MetaMaskProvider类中新增sendTransaction方法,用于构造交易参数并唤起MetaMask让用户确认交易:

import 'package:flutter/cupertino.dart';
import 'package:flutter_web3/flutter_web3.dart';

class MetaMaskProvider extends ChangeNotifier {
  static const operatingChain = 4; // Rinkeby测试链

  String currentAddress = '';
  int currentChain = 80001;

  // ... 保留原有connect、clear、init方法 ...

  Future<String?> sendTransaction({
    required String toAddress,
    required BigInt value, // 交易金额,单位为Wei(1 ETH = 1e18 Wei)
    BigInt? gasLimit,
    BigInt? gasPrice,
  }) async {
    // 先检查连接状态与链匹配情况
    if (!isConnected) {
      throw Exception('未连接MetaMask,请先完成连接');
    }
    if (!isInOperatingChain) {
      throw Exception('当前链不匹配,请切换到链ID ${operatingChain}');
    }

    try {
      // 构造标准以太坊交易参数
      final transactionParams = {
        'from': currentAddress, // 必须是当前已授权的地址
        'to': toAddress, // 接收方钱包地址
        'value': '0x${value.toRadixString(16)}', // 转换为十六进制字符串
        if (gasLimit != null) 'gasLimit': '0x${gasLimit.toRadixString(16)}',
        if (gasPrice != null) 'gasPrice': '0x${gasPrice.toRadixString(16)}',
      };

      // 调用MetaMask的eth_sendTransaction RPC方法
      final txHash = await ethereum!.request(
        method: 'eth_sendTransaction',
        params: [transactionParams],
      );

      notifyListeners();
      return txHash; // 返回交易哈希,用于后续查询交易状态
    } catch (e) {
      // 捕获用户拒绝交易、链不兼容等错误
      print('交易失败: $e');
      rethrow;
    }
  }
}

2. UI层调用示例

在你的Flutter Web页面中,通过Provider调用该方法即可触发交易:

// 假设通过Provider获取MetaMaskProvider实例
final metaMaskProvider = Provider.of<MetaMaskProvider>(context, listen: false);

// 示例:发送0.01 ETH到指定地址
ElevatedButton(
  onPressed: () async {
    try {
      // 0.01 ETH转换为Wei:0.01 * 10^18
      final amountWei = BigInt.from(0.01 * 1e18);
      final txHash = await metaMaskProvider.sendTransaction(
        toAddress: '0xYourRecipientWalletAddress', // 替换为实际接收地址
        value: amountWei,
      );
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('交易已提交,哈希:$txHash')),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('交易失败:$e')),
      );
    }
  },
  child: const Text('发起支付'),
)

关键注意事项

  • 金额单位转换:以太坊交易默认使用Wei作为单位,1 ETH = 10^18 Wei。你也可以使用flutter_web3提供的EtherAmount工具类简化转换:
    final amountWei = EtherAmount.fromUnitAndValue(EtherUnit.ether, 0.01).getInWei;
    
  • 链ID检查:确保用户的MetaMask已切换到你指定的operatingChain(示例中为Rinkeby链ID 4),否则交易会被拒绝。
  • 异常处理:必须捕获交易过程中的异常,比如用户主动拒绝交易、网络问题等,避免应用崩溃。

内容的提问来源于stack exchange,提问作者Ganesh Sivakumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:40:23