You need to enable JavaScript to run this app. Flutter访问API返回JSON时报Object类型未定义[]运算符错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Flutter访问API返回JSON时报Object类型未定义[]运算符错误如何解决

Flutter接口数据取值报错解决方法

报错核心原因

你没有给FutureBuilder指定泛型类型,Dart默认将SnapShot.data推断为Object类型,Object类型原生不支持[]下标操作,所以触发The operator '[]' isn't defined for the type 'Object'报错。

修复步骤

  • 给FutureBuilder添加泛型约束,明确其承载的异步返回数据是List类型,将原代码中FutureBuilder(修改为FutureBuilder<List>(
  • 可选优化:结合空安全特性做值判空,避免运行时异常,将报错行的Text组件修改为:
Text(
    SnapShot.data?[index]['country'] ?? '未知国家',
    style: TextStyle(color: Colors.white,fontSize: 18.0,fontWeight: FontWeight.bold),
)

修正后的FutureBuilder完整代码

FutureBuilder<List>(
    future: datas,
    builder:( BuildContext context, SnapShot){
        if(SnapShot.hasData){
            return GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10,
                    childAspectRatio: 1.0,
                ),
                itemBuilder: (BuildContext context, index) => SizedBox(
                    height: 50,
                    width: 50,
                    child: GestureDetector(
                        onTap: (){},
                        child: Card(
                            child: Container(
                                color: Colors.amberAccent,
                                child: Center(
                                    child: Column(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                        children: <Widget>[
                                            Image(image: AssetImage("images/wdeath.png",),height: 85,width: 85,),
                                            Text(
                                                SnapShot.data?[index]['country'] ?? '未知国家',
                                                style: TextStyle(color: Colors.white,fontSize: 18.0,fontWeight: FontWeight.bold),
                                            ),
                                        ],
                                    ),
                                ),
                            ),
                        ),
                    ),
                )
            );
        }else{
            return Center(child: CircularProgressIndicator(),);
        }
    },
)

内容的提问来源于stack exchange,提问作者Lohith Manideep

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 06:51:05