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

Flutter调用CoinGecko API获取JSON数据转列表后如何在Widget正确展示

问题解决方案

你遇到的问题由3个核心原因导致,依次修复即可正常获取数据并展示:

  • 第一,Coin类构造函数未正确绑定coinImgUrl、coinVol两个属性,导致这两个字段始终为空
  • 第二,异步请求完成后未调用setState通知Flutter状态变更,UI不会触发重绘
  • 第三,Dart普通类默认toString方法仅输出实例类型,需重写才能打印属性内容

第一步:修复Coin类定义

修正构造函数参数绑定,同时重写toString方法方便调试:

class Coin {
  String? coinName;
  String? coinPrice;
  String? coinImgUrl;
  String? coinVol;
  Coin({
    required this.coinName, // 空安全版本下建议用required替代旧的@required
    required this.coinPrice,
    required this.coinImgUrl,
    required this.coinVol,
  });

  @override
  String toString() {
    return '{coinName: $coinName, coinPrice: $coinPrice, coinVol: $coinVol, coinImgUrl: $coinImgUrl}';
  }
}

第二步:修正initState逻辑,添加setState通知UI更新

@override
void initState() {
  super.initState();
  _isLoading = true;
  Coins().fetchCoinsData().then((List<Coin> value) {
    // 调用setState更新状态,触发页面重绘
    setState(() {
      my_list = value;
      _isLoading = false;
    });
    // 此时打印就会输出你期望的属性内容
    print(my_list);
  });
}

第三步:Widget中直接访问Coin实例属性完成展示

示例用ListView展示币种列表:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: const Text("加密货币行情")),
    body: _isLoading == true 
      ? const Center(child: CircularProgressIndicator())
      : ListView.builder(
          padding: const EdgeInsets.all(12),
          itemCount: my_list.length,
          itemBuilder: (context, index) {
            final coin = my_list[index];
            return Card(
              margin: const EdgeInsets.only(bottom: 8),
              child: Padding(
                padding: const EdgeInsets.all(12),
                child: Row(
                  children: [
                    Image.network(coin.coinImgUrl ?? '', width: 32, height: 32),
                    const SizedBox(width: 12),
                    Expanded(child: Text(coin.coinName?.toUpperCase() ?? '--', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500))),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text('\$ ${coin.coinPrice ?? '--'}', style: const TextStyle(fontSize: 16, color: Colors.green)),
                        Text('成交量: ${coin.coinVol ?? '--'}', style: const TextStyle(fontSize: 12, color: Colors.grey)),
                      ],
                    )
                  ],
                ),
              ),
            );
          },
        ),
  );
}

内容的提问来源于stack exchange,提问作者Rintu Banerjee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:36:06