Flutter区块链交互插件flutter_web3_provider的使用

发布于 1周前 作者 zlyuanteng 来自 Flutter

Flutter区块链交互插件flutter_web3_provider的使用

引言

flutter_web3_provider 是是一个用于在Flutter应用中与Web3提供程序(如window.ethereum)进行交互的封装。它允许开发者轻松地访问和操作以太坊网络。

安装示例

首先,确保你已经安装了flutter_web3_provider包。如果还没有安装,可以通过以下命令安装:

flutter pub add flutter_web3_provider

示例代码

下面是一个完整的示例代码,展示了如何使用flutter_web3_provider来连接钱包、获取余额以及发送交易。

import 'package:flutter/material.dart';
import 'package:flutter_web3_provider/ethereum.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Web3 Provider Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? selectedAddress;
  Future<void>? balanceF;
  Future<void>? usdcBalanceF;

  @override
  void initState() {
    super.initState();
    if (ethereum != null) {
      print("ethereum: ${ethereum}");
      print("ethereum.selectedAddress: ${ethereum!.selectedAddress}");
      balanceF = promiseToFuture(ethereum!.getBalance(ethereum!.selectedAddress));
      var contract = Contract('0x97a19AD88726d7Eca45515814cdeF75AcC4f713', [], web3);
      usdcBalanceF = promiseToFuture(callMethod(contract, "balanceOf", [ethereum!.selectedAddress]));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Web3 Provider Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Connected Address: $selectedAddress'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                var accounts = await promiseToFuture(ethereum!.request(RequestParams(method: 'eth_requestAccounts')));
                setState(() {
                  selectedAddress = accounts[0];
                });
              },
              child: Text('Connect Wallet'),
            ),
            SizedBox(height: 22),
            Text('Native Balance:'),
            FutureBuilder(
              future: balanceF,
              builder: (context, snapshot) {
                if (snapshot.hasError {
                  return Text('Error: ${snapshot.error}');
                } else if !snapshot.hasData {
                  return CircularProgressIndicator();
                }
                var big = BigInt.parse(snapshot.data.toString());
                var d = toDecimal(big, 18);
                return Text('${d}');
              },
            ),
            SizedBox(height: 22),
            Text('USDC Balance:'),
            FutureBuilder(
              future: usdcBalanceF,
              builder: (context, snapshot) {
                if snapshot.hasError {
                  return Text('Error: ${snapshot.error}');
                } else if !snapshot.hasData {
                  return CircularProgressIndicator();
                }
                var big = BigInt.parse(snapshot.data.toString());
                var d = toDecimal(big, 6);
                return Text('${d}');
              },
            ),
            ElevatedButton(
              onPressed: () async {
                try {
                  // DEprecated:
                  // var res = await promiseToFuture(contract.transfer(
                  //   '0x39C5190c09ec04cF09C782bA4311C469473Ffe83',
                  //   "0x" + BigInt.parse(toBase(Decimal.parse("0.01"), 6).toString()).toRadixString(16)));
                  // Use this instead:
                  var res = await promiseToFuture(callMethod(contract, "transfer", [
                    '0x39C5190c09ec04cF09C782bA4311C469473Ffe83',
                    "0x" + BigInt.parse(toBase(Decimal.parse("0.01"), 6).toString()).toRadixString(16)
                  ]));
                  print('Transferred: ${res.toString()}');
                } catch (e) {
                  print('Exception: $e');
                }
              },
              child: Text('Transfer $0.01'),
            ),
            SizedBox(height: 22),
            ElevatedButton(
              onPressed: () async {
                var signer = await promiseToFuture(web3!.getSigner());
                print('signer: ${signer}');
                var signature = await promiseToFuture(signer.signMessage('Sign this message'));
                print('Signature: $signature');
              },
              child: Text('Sign Message'),
            ),
            SizedBox(height: 22),
            TextField(
              maxLines: 4,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
              ),
              controller: TextEditingController(),
            ),
            ElevatedButton(
              onPressed: () async {
                var verified = verifyMessage('Sign this message', _controller.text);
                print('verified?: $verified');
              },
              child: Text('Verify Signature'),
            ),
            SizedBox(height: 22),
            TextField(
              maxLines: 4,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
              ),
              controller: TextEditingController(),
            ),
          ],
        ),
      ),
    );
  }
}

使用说明

  1. 导入包

    import 'package:flutter_web3_provider/ethereum.dart';
    
  2. 初始化

    if (ethereum != null) {
      print("ethereum: ${ethereum}");
      print("ethereum.selectedAddress: ${ethereum!.selectedAddress}");
      balanceF = promiseToFuture(ethereum!.getBalance(ethereum!.selectedAddress));
      var contract = Contract('0x97a19AD88722d7Eca45515814cdeF75AcC4g713', [], web3);
      usdcBalanceF = promiseToFuture(callMethod(contract, "balanceOf", [ethereum!.selectedAddress]));
    }
    
  3. 连接钱包

    ElevatedButton(
      onPressed: () async {
        var accounts = await promiseToFuture(ethereum!.request(RequestParams(method: 'eth_requestAccounts')));
        setState(() {
          selectedAddress = accounts[0];
        });
      },
      child: Text('Connect Wallet'),
    ),
    
  4. 获取余额

    FutureBuilder(
      future: balanceF,
      builder: (context, snapshot) {
        if snapshot.hasError {
          return Text('Error: ${snapshot.error}');
        } else if !snapshot.hasData {
          return CircularProgressIndicator();
        }
      var big = BigInt.parse(snapshot.data.toString());
      var d = toDecimal(big, 18);
      return Text('${d}');
    },
    )
    
  5. 发送交易

    ElevatedButton(
      onPressed: () async {
        try {
          // Deprecated:
          // var res = await promiseToFuture(contract.transfer(
          //   '0x39C5190c09ec04cF09C782bA4311C449473Ffe83',
          //   "0x" + BigInt.parse(toBase(Decimal.parse("0.01"), 6).toString()).toRadixString(16)));
          // Use this instead:
          var res = await promiseToFuture(callMethod(contract, "transfer", [
            '0x39C5190c09ec04cF09C782bA4311C449473Ffe83',
            "0x" + BigInt.parse(toBase(Decimal.parse("0.01"), 6).toString()).toRadixString(16)
          ]));
          print('Transferred: ${res.toString()}');
        } catch (e) {
          print('Exception: $e');
        }
      },
      child: Text('Transfer $0.01'),
    ),
    
  6. 签名消息

    ElevatedButton(
      onPressed: () async {
        var signer = await promiseToFuture(web3!.getSigner());
        print('signer: ${signer}');
        var signature = await promiseToFuture(signer.signMessage('Sign this message'));
        print('Signature: $signature');
      },
      child: Text('Sign Message'),
    ),
    
  7. 验证签名

    ElevatedButton(
      onPressed: () async {
        var verified = verifyMessage('Sign this message', _controller.text);
        print('verified?: $verified');
      },
      child: Text('Verify Signature'),
    ),
    

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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_web3_provider插件与区块链进行交互的示例代码。这个插件允许Flutter应用通过Web3提供者(如MetaMask)与以太坊区块链进行交互。

首先,确保你的Flutter环境已经配置好,并且已经创建了一个新的Flutter项目。然后,按照以下步骤操作:

1. 添加依赖

在你的pubspec.yaml文件中添加flutter_web3_provider依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_web3_provider: ^x.y.z  # 替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 配置Web3 Provider

在你的Flutter项目中,你需要配置Web3提供者。这通常是在你的主页面或初始化代码中完成的。

import 'package:flutter/material.dart';
import 'package:flutter_web3/flutter_web3.dart';
import 'package:flutter_web3_provider/flutter_web3_provider.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Web3 Provider Example'),
        ),
        body: Web3ProviderExample(),
      ),
    );
  }
}

class Web3ProviderExample extends StatefulWidget {
  @override
  _Web3ProviderExampleState createState() => _Web3ProviderExampleState();
}

class _Web3ProviderExampleState extends State<Web3ProviderExample> {
  late Web3Provider web3Provider;
  late Ethereum? ethereum;

  @override
  void initState() {
    super.initState();
    web3Provider = Web3Provider();
    initWeb3();
  }

  Future<void> initWeb3() async {
    // 请求用户连接MetaMask或其他Web3钱包
    bool isConnected = await web3Provider.requestAccounts();
    if (isConnected) {
      List<String> accounts = await web3Provider.getAccounts();
      String firstAccount = accounts.isNotEmpty ? accounts.first : '';

      // 使用Web3Provider获取Ethereum实例
      ethereum = await web3Provider.getEthereum(firstAccount);

      // 你可以在这里执行其他区块链操作,例如获取余额、发送交易等
      // 例如:获取余额
      BigInt balance = await ethereum?.getBalance(firstAccount);
      print('Balance: $balance');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Connecting to Web3 Provider...'),
          // 你可以在这里添加按钮或其他UI元素来触发交易或其他操作
        ],
      ),
    );
  }
}

3. 注意事项

  • 确保你的网页或应用已经正确设置了MetaMask或其他Web3钱包的访问权限。
  • 在实际项目中,处理用户账户和交易时需要格外注意安全性,避免敏感信息泄露。
  • 异步操作(如请求账户和获取余额)需要妥善处理,以避免潜在的UI卡顿或错误。

4. 运行项目

确保你的开发环境支持Web3(例如,在Chrome浏览器中运行Flutter Web应用),然后运行你的Flutter项目:

flutter run -d chrome

如果一切配置正确,你的Flutter应用应该能够请求Web3提供者并与之交互,从而获取账户信息、余额等。

请注意,这只是一个简单的示例,实际项目中可能需要更复杂的逻辑和错误处理。希望这个示例能帮助你入门使用flutter_web3_provider插件。

回到顶部