Flutter网络图标加载插件flutter_icon_network的使用

Flutter网络图标加载插件flutter_icon_network的使用

flutter_icon_network 是一个用于加载网络图标的Flutter插件。本文档将介绍如何安装和使用该插件。

版本

当前版本为 1.0.0

前提条件

  • Dart 版本:>=2.12.0 <3.0.0
  • Flutter 版本:>=2.4.0

安装

pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter_icon_network: ^1.0.0

或者从特定的 Git 仓库中安装:

dependencies:
  flutter_icon_network:
    git:
      url: https://git.baikal.io/mobile/boilerplate/flutter_icon_network

快速开始

我们提供了一些不同类型的代码示例帮助你快速上手。以下是一个简单的项目示例。

示例代码

以下是 main.dart 的示例代码:

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_icon_network/flutter_icon_network.dart';
import 'package:flutter_icon_network_example/constants.dart';
import 'package:flutter_icon_network_example/widgets/button.dart';
import 'package:get_storage/get_storage.dart';
import 'package:url_launcher/url_launcher.dart';

void main() async {
  await GetStorage.init();
  await FlutterIconNetwork.instance!
      .init(host: "https://bicon.net.solidwallet.io/api/v3", isTestNet: true);
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late BuildContext scaffoldContext;
  final privateKeyCtrl = TextEditingController();
  final walletAddressCtrl = TextEditingController();
  double? currentIcxBalance;
  double? currentTokenBalance;
  String txHash = "";
  String? lastBlockId;
  String? tokenName;
  String? tokenSymbol;
  List<String>? confirmedTransationList;
  Map<String, dynamic>? _transactionResult;
  String? _blockByHeight, _blockByHash, _totalSupply, _scoreAPIs;
  Map<String, String>? _walletByPrivateKey;

  // send icx
  final icxSenderCtrl = TextEditingController();
  final icxReceiverCtrl = TextEditingController();
  final icxSendAmountCtrl = TextEditingController();

  // score
  final scoreAddressCtrl = TextEditingController();
  final tokenReceiverAddressCtrl = TextEditingController();
  final tokenSendAmountCtrl = TextEditingController();

  @override
  void initState() {
    super.initState();
    icxSenderCtrl.text = IconConstant.samplePrivateKey;
    Future.delayed(Duration(seconds: 1), () {
      _getCache();
    });
  }

  @override
  void dispose() {
    privateKeyCtrl.dispose();
    walletAddressCtrl.dispose();
    icxSenderCtrl.dispose();
    icxReceiverCtrl.dispose();
    icxSendAmountCtrl.dispose();
    scoreAddressCtrl.dispose();
    tokenReceiverAddressCtrl.dispose();
    tokenSendAmountCtrl.dispose();
    super.dispose();
  }

  void _createWallet() async {
    final wallet = await FlutterIconNetwork.instance!.createWallet;
    setState(() {
      privateKeyCtrl.text = wallet.privateKey!;
      walletAddressCtrl.text = wallet.address!;
      icxReceiverCtrl.text = wallet.address!;
    });
    _saveCache();
  }

  void _sendIcx() async {
    final response = await FlutterIconNetwork.instance!.sendIcx(
        yourPrivateKey: icxSenderCtrl.text,
        destinationAddress: icxReceiverCtrl.text,
        value: icxSendAmountCtrl.text);
    _showSnackBar(
      "transaction hash ${response.txHash} copied, pls press check txHash button to check",
    );
    Clipboard.setData(new ClipboardData(text: response.txHash));
    setState(() {
      txHash = "transaction/${response.txHash}";
    });
    Future.delayed(Duration(seconds: 5), () async {
      _getIcxBalance();
    });
  }

  void _getIcxBalance() async {
    final balance = await FlutterIconNetwork.instance!
        .getIcxBalance(privateKey: privateKeyCtrl.text);
    setState(() {
      currentIcxBalance = balance.icxBalance;
    });
    _saveCache();
  }

  void _sendToken() async {
    final response = await FlutterIconNetwork.instance!.sendToken(
        yourPrivateKey: privateKeyCtrl.text,
        toAddress: tokenReceiverAddressCtrl.text,
        value: tokenSendAmountCtrl.text,
        scoreAddress: scoreAddressCtrl.text);
    _showSnackBar(
      "transaction hash ${response.txHash} copied, pls press check txHash button to check",
    );
    Clipboard.setData(new ClipboardData(text: response.txHash));
    setState(() {
      txHash = "transaction/${response.txHash}";
    });
    Future.delayed(Duration(seconds: 5), () async {
      _getTokenBalance();
    });
  }

  void _getTokenBalance() async {
    final balance = await FlutterIconNetwork.instance!.getTokenBalance(
        privateKey: privateKeyCtrl.text, scoreAddress: scoreAddressCtrl.text);
    setState(() {
      currentTokenBalance = balance.icxBalance;
    });
    _saveCache();
  }

  void _deployScore() async {
    final transactionResult = await (FlutterIconNetwork.instance!
        .deployScore(privateKey: privateKeyCtrl.text, initIcxSupply: "10"));
    if (transactionResult == null) return;
    setState(() {
      scoreAddressCtrl.text = transactionResult.scoreAddress!;
      txHash = "transaction/${transactionResult.txHash}";
    });
    _showSnackBar(
        "deployed, scoreAddress ${transactionResult.scoreAddress} copied, "
        "please press check txHash button to check");
  }

  void _getLastBlock() async {
    final lastBlock = await FlutterIconNetwork.instance!.getLastBlock();
    if (lastBlock == null) return;

    setState(() {
      lastBlockId = lastBlock;
    });
  }

  void _getTransactionList() async {
    final transactionList =
        await FlutterIconNetwork.instance!.getConfirmedTransactionIdList();

    if (transactionList == null) return;

    setState(() {
      confirmedTransationList = transactionList;
    });
  }

  void _getTokenName() async {
    final name = await FlutterIconNetwork.instance!.checkScoreTokenName(
      "cx9e7f89f7f7fa8bd5d56e67282328a3ca87a082b1",
    );

    if (name == null) return;

    setState(() {
      tokenName = name;
    });
  }

  void _getTokenSymbol() async {
    final symbol = await FlutterIconNetwork.instance!.checkScoreTokenSymbol(
      "cx9e7f89f7f7fa8bd5d56e67282328a3ca87a082b1",
    );

    if (symbol == null) return;

    setState(() {
      tokenSymbol = symbol;
    });
  }

  void _getTransactionResult() async {
    final tResult = await FlutterIconNetwork.instance!.getTransactionResult(
        "0x884913fbb472338fa5f05d46d2646364aaaa5f0e384d9a2612c901955ae0befe");

    if (tResult == null) return;

    setState(() {
      _transactionResult = tResult;
    });
  }

  void _getBlockByHeight() async {
    final blockByHeight =
        await FlutterIconNetwork.instance!.getBlockByHeight("20519341");

    if (blockByHeight == null) return;

    setState(() {
      _blockByHeight = blockByHeight.toString();
    });
  }

  void _getBlockByHash() async {
    final blockByHash = await FlutterIconNetwork.instance!.getBlockByHash(
        "0x4703fca6a93e6b7fb6da497a14da4b34f4f775c82f243c300c66cc41a011aeed");

    if (blockByHash == null) return;

    setState(() {
      _blockByHash = blockByHash.toString();
    });
  }

  void _getBlockTotalSupply() async {
    final totalSupply = await FlutterIconNetwork.instance!.getTotalSupply();

    if (totalSupply == null) return;

    setState(() {
      _totalSupply = totalSupply;
    });
  }

  void _getScoreAPIs() async {
    final scoreAPIs = await FlutterIconNetwork.instance!
        .getScoreAPIs("cx9e7f89f7f7fa8bd5d56e67282328a3ca87a082b1");

    if (scoreAPIs == null) return;

    setState(() {
      _scoreAPIs = scoreAPIs.toString();
    });
  }

  void _getWalletByPrivateKey() async {
    final wallet = await FlutterIconNetwork.instance!.getWalletByPrivateKey(
        "592eb276d534e2c41a2d9356c0ab262dc233d87e4dd71ce705ec130a8d27ff0c");

    if (wallet == null) return;

    setState(() {
      _walletByPrivateKey = wallet;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Icon Network Example'),
        ),
        body: Builder(
          builder: (scaffoldContext) {
            this.scaffoldContext = scaffoldContext;
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ..._buildWalletSection(),
                    Padding(
                      padding: const EdgeInsets.all(16),
                    ),
                    ..._buildSendIcxSection(),
                    Padding(
                      padding: const EdgeInsets.all(16),
                    ),
                    ..._buildGetIcxBalanceSection(),
                    Padding(
                      padding: const EdgeInsets.all(20),
                      child: Divider(),
                    ),
                    ..._buildScoreSection(),
                    Padding(
                      padding: const EdgeInsets.all(16),
                    ),
                    ..._buildSendTokenSection(),
                    Padding(
                      padding: const EdgeInsets.all(16),
                    ),
                    ..._buildGetTokenBalanceSection(),
                    SizedBox(height: 50),
                    _buildGetLastBlockInfo(),
                    SizedBox(height: 50),
                    _buildTokenName(),
                    SizedBox(height: 50),
                    _buildTokenSymbol(),
                    SizedBox(height: 50),
                    _buildConfirmedTransactionList(),
                    SizedBox(height: 50),
                    _buildTransactionResult(),
                    SizedBox(height: 50),
                    _buildBlockByHeight(),
                    SizedBox(height: 50),
                    _buildBlockByHash(),
                    SizedBox(height: 50),
                    _buildBlockTotalSupply(),
                    SizedBox(height: 50),
                    _buildScoreAPIs(),
                    SizedBox(height: 50),
                    _buildGetWalletByPrivateKey(),
                    SizedBox(height: 50),
                    AppSolidButton(
                      backgroundColor: Colors.red,
                      width: 200,
                      onTap: () {
                        launch("https://bicon.tracker.solidwallet.io/$txHash");
                      },
                      text: "Check transaction hash",
                    ),
                    SizedBox(height: 10),
                    AppSolidButton(
                      backgroundColor: Colors.red,
                      width: 200,
                      onTap: () {
                        launch(
                          "https://bicon.tracker.solidwallet.io/address/${walletAddressCtrl.text}",
                        );
                      },
                      text: "Check wallet address",
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  // icx
  List<Widget> _buildWalletSection() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AppSolidButton(onTap: _createWallet, text: "Create wallet"),
          SizedBox(width: 10),
          Expanded(child: TextField(controller: privateKeyCtrl)),
          SizedBox(width: 10),
          Expanded(child: TextField(controller: walletAddressCtrl))
        ],
      ),
      SizedBox(height: 10),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(width: 110),
          Expanded(child: Center(child: _buildHint("privateKey"))),
          SizedBox(width: 10),
          Expanded(child: Center(child: _buildHint("walletAddress"))),
        ],
      )
    ];
  }

  List<Widget> _buildSendIcxSection() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AppSolidButton(onTap: _sendIcx, text: "Send ICX"),
          SizedBox(width: 10),
          Expanded(child: TextField(controller: icxSenderCtrl)),
          SizedBox(width: 10),
          Expanded(child: TextField(controller: icxReceiverCtrl)),
          SizedBox(width: 10),
          Expanded(child: TextField(controller: icxSendAmountCtrl))
        ],
      ),
      SizedBox(
        height: 10,
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(width: 100),
          SizedBox(width: 10),
          Expanded(child: Center(child: _buildHint("privateKey"))),
          SizedBox(width: 10),
          Expanded(child: Center(child: _buildHint("to"))),
          SizedBox(width: 10),
          Expanded(child: Center(child: _buildHint("value"))),
        ],
      )
    ];
  }

  List<Widget> _buildGetIcxBalanceSection() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AppSolidButton(onTap: _getIcxBalance, text: "Get Icx balance"),
          SizedBox(width: 10),
          Expanded(
              child: Center(
                  child: Text(currentIcxBalance != null
                      ? "$currentIcxBalance ICX"
                      : "N/A"))),
        ],
      ),
      SizedBox(
        height: 10,
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(width: 100),
          SizedBox(width: 10),
          Expanded(child: Center(child: _buildHint("current balance"))),
        ],
      )
    ];
  }

  List<Widget> _buildGetTokenBalanceSection() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AppSolidButton(onTap: _getTokenBalance, text: "Get Token balance"),
          SizedBox(width: 10),
          Expanded(
              child: Center(
                  child: Text(currentTokenBalance != null
                      ? "$currentTokenBalance Token"
                      : "N/A"))),
        ],
      ),
      SizedBox(height: 10),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(width: 110),
          Expanded(child: Center(child: _buildHint("current balance"))),
        ],
      )
    ];
  }

  // score
  List<Widget> _buildScoreSection() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AppSolidButton(
            onTap: _deployScore,
            text: "Create SCORE",
            isEnable: Platform.isAndroid,
          ),
          SizedBox(width: 10),
          Expanded(child: TextField(controller: scoreAddressCtrl)),
        ],
      ),
      SizedBox(
        height: 10,
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(width: 100),
          SizedBox(width: 10),
          Expanded(child: Center(child: _buildHint("SCORE Address"))),
        ],
      )
    ];
  }

  List<Widget> _buildSendTokenSection() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AppSolidButton(onTap: _sendToken, text: "Send Token"),
          SizedBox(width: 10),
          Expanded(child: TextField(controller: tokenReceiverAddressCtrl)),
          SizedBox(width: 10),
          Expanded(child: TextField(controller: tokenSendAmountCtrl))
        ],
      ),
      SizedBox(height: 10),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(width: 100),
          SizedBox(width: 10),
          Expanded(child: Center(child: _buildHint("Token Receiver Address"))),
          SizedBox(width: 10),
          Expanded(child: Center(child: _buildHint("amount of token"))),
        ],
      )
    ];
  }

  void _saveCache() {
    GetStorage().write(StorageKey.icxBalance, currentIcxBalance);
    GetStorage().write(StorageKey.privateKey, privateKeyCtrl.text);
    GetStorage().write(StorageKey.walletAddress, walletAddressCtrl.text);
    GetStorage().write(StorageKey.icxSender, icxSenderCtrl.text);
    GetStorage().write(StorageKey.icxReceiver, icxReceiverCtrl.text);
    GetStorage().write(StorageKey.icxSendAmount, icxSendAmountCtrl.text);

    // score
    GetStorage().write(StorageKey.tokenBalance, currentTokenBalance);
    GetStorage().write(StorageKey.scoreAddress, scoreAddressCtrl.text);
    GetStorage().write(StorageKey.tokenReceiver, tokenReceiverAddressCtrl.text);
    GetStorage().write(StorageKey.tokenSendAmount, tokenSendAmountCtrl.text);
  }

  void _getCache() {
    setState(() {
      currentIcxBalance = GetStorage().read<double>(StorageKey.icxBalance);
      privateKeyCtrl.text =
          GetStorage().read<String>(StorageKey.privateKey) ?? "";
      walletAddressCtrl.text =
          GetStorage().read<String>(StorageKey.walletAddress) ?? "";
      icxSenderCtrl.text =
          GetStorage().read<String>(StorageKey.icxSender) ?? "";
      icxReceiverCtrl.text =
          GetStorage().read<String>(StorageKey.icxReceiver) ?? "";
      icxSendAmountCtrl.text =
          GetStorage().read<String>(StorageKey.icxSendAmount) ?? "";

      // score
      currentTokenBalance = GetStorage().read(StorageKey.tokenBalance);
      scoreAddressCtrl.text = GetStorage().read<String>(StorageKey.scoreAddress) ?? "";
      tokenReceiverAddressCtrl.text =
          GetStorage().read<String>(StorageKey.tokenReceiver) ?? "";
      tokenSendAmountCtrl.text =
          GetStorage().read<String>(StorageKey.tokenSendAmount) ?? "";
    });
  }

  void _showSnackBar(String text) {
    Scaffold.of(scaffoldContext).showSnackBar(SnackBar(content: Text(text)));
  }

  Text _buildHint(String text) {
    return Text(
      text,
      style: TextStyle(color: Colors.grey, fontSize: 10),
    );
  }

  Widget _buildGetLastBlockInfo() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        AppSolidButton(onTap: _getLastBlock, text: "Get last block"),
        SizedBox(width: 10.0),
        Expanded(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(lastBlockId ?? "N/A"),
              SizedBox(height: 10.0),
              _buildHint("Last block info"),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildConfirmedTransactionList() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        AppSolidButton(
            onTap: _getTransactionList, text: "Get transaction list"),
        SizedBox(width: 10.0),
        Expanded(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (confirmedTransationList != null && confirmedTransationList?.length != 0)
                ...List.generate(confirmedTransationList!.length,
                    (index) => Text(confirmedTransationList![index]))
              else
                Text("N/A"),
              SizedBox(height: 10.0),
              _buildHint("Transaction list"),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildTokenName() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        AppSolidButton(onTap: _getTokenName, text: "Check token name"),
        Expanded(
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(tokenName ?? "N/A"),
                SizedBox(height: 10.0),
                _buildHint("Token name"),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTokenSymbol() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        AppSolidButton(onTap: _getTokenSymbol, text: "Check token symbol"),
        Expanded(
          child: Center(
            child: Column(
              children: [
                Text(tokenSymbol ?? "N/A"),
                SizedBox(height: 10.0),
                _buildHint("Token symbol"),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTransactionResult() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        AppSolidButton(
            onTap: _getTransactionResult, text: "Get transaction result"),
        SizedBox(width: 10.0),
        Expanded(
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(_transactionResult?.toString() ?? "N/A"),
                SizedBox(height: 10.0),
                _buildHint("Transaction result"),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildBlockByHeight() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        AppSolidButton(onTap: _getBlockByHeight, text: "Get block by height"),
        SizedBox(width: 10.0),
        Expanded(
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(_blockByHeight ?? "N/A"),
                SizedBox(height: 10.0),
                _buildHint("Block by height"),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildBlockByHash() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        AppSolidButton(onTap: _getBlockByHash, text: "Get block by hash"),
        SizedBox(width: 10.0),
        Expanded(
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(_blockByHash ?? "N/A"),
                SizedBox(height: 10.0),
                _buildHint("Block by hash"),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildBlockTotalSupply() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        AppSolidButton(
            onTap: _getBlockTotalSupply, text: "Get block's total supply"),
        SizedBox(width: 10.0),
        Expanded(
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(_totalSupply ?? "N/A"),
                SizedBox(height: 10.0),
                _buildHint("Block's total supply"),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildScoreAPIs() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        AppSolidButton(onTap: _getScoreAPIs, text: "Get SCORE APIs"),
        SizedBox(width: 10.0),
        Expanded(
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(_scoreAPIs ?? "N/A"),
                SizedBox(height: 10.0),
                _buildHint("SCORE APIs"),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildGetWalletByPrivateKey() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        AppSolidButton(
            onTap: _getWalletByPrivateKey, text: "Get wallet by private key"),
        SizedBox(width: 10.0),
        Expanded(
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(_walletByPrivateKey?.toString() ?? "N/A"),
                SizedBox(height: 10.0),
                _buildHint("Wallet by private key"),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

使用说明

创建钱包

final wallet = await FlutterIconNetwork.instance!.createWallet;
print("address": "${wallet['address']}");
print("privateKey": "${wallet['private_key']}");

加载钱包

final wallet = await FlutterIconNetwork.instance.getWalletByPrivateKey(/*YOUR_PRIVATE_KEY*/);
print("address": "${wallet['address']}");
print("privateKey": "${wallet['private_key']}");

发送 ICX

final txHash = await FlutterIconNetwork.instance.sendIcx(
  yourPrivateKey: /*YOUR_PRIVATE_KEY*/,
  destinationAddress: /*RECEIVE_ADDRESS*/,
  value: 1
);
print("txHash $txHash");

检查 ICX 余额

final balance = await FlutterIconNetwork.instance.getIcxBalance(privateKey: /*YOUR_PRIVATE_KEY*/);
print("balance: $balance");

更多关于Flutter网络图标加载插件flutter_icon_network的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网络图标加载插件flutter_icon_network的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter中使用flutter_icon_network插件来加载网络图标的示例代码。

首先,确保你已经在pubspec.yaml文件中添加了flutter_icon_network依赖:

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

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

接下来,你可以在你的Flutter项目中使用NetworkImageIcon组件来加载网络图标。以下是一个完整的示例代码:

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

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

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

class MyHomePage extends StatelessWidget {
  final String iconUrl =
      'https://example.com/path/to/your/icon.png';  // 替换为你的图标URL

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Network Icon Loader'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            NetworkImageIcon(
              iconUrl,
              size: 64,  // 图标大小
              color: Colors.black,  // 图标颜色(可选)
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // 你可以在这里添加点击事件处理逻辑
                print('Icon tapped');
              },
              child: Text('Tap Me'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们做了以下几件事:

  1. pubspec.yaml文件中添加了flutter_icon_network依赖。
  2. MyApp中设置了基本的Material应用。
  3. MyHomePage中,我们定义了一个网络图标的URL,并使用NetworkImageIcon组件加载该图标。
  4. 我们设置了图标的大小和颜色(颜色参数是可选的)。
  5. 添加了一个按钮,用于演示如何在图标旁边添加其他组件或处理点击事件。

确保将iconUrl变量替换为你实际使用的网络图标的URL。

这样,你就可以在Flutter应用中加载和显示网络图标了。

回到顶部