【问题标题】:How to fix 'NoSuchMethodError: The getter 'length' was called on null'如何修复'NoSuchMethodError:getter'length'被调用为null'
【发布时间】:2019-08-24 18:21:13
【问题描述】:

我该如何解决这个问题 我使用函数从 api 获取数据,但我看到错误 'NoSuchMethodError: The getter 'length' was called on null'

我的代码:

Future getData() async{
http.Response response = await http.get('https://myappres.000webhostapp.com/pubg/api.php?action=getskin');
debugPrint(response.body);

_data = json.decode(response.body);
_list = _data['categorys'];

return _list;                                                               
}

 Center(
          child: _list.length != null? ListView.builder(
              itemCount: _list.length,
              padding: const EdgeInsets.all(15.9),
              itemBuilder: (BuildContext context, int position){
                final index = position;
                return ListTile(
                    title: Text('${_list[index]['name']}'),
                    subtitle: Image.network('${_list[index]['image']}',width: 200,)
                );
              }
          ):Container()
        )

这是结果错误:

【问题讨论】:

标签: flutter


【解决方案1】:

尝试使用 FutureBuilder 等待 Future:

FutureBuilder(
      future: getData(),
      builder: (BuildContext context,AsyncSnapshot<List> snapshot){
        if(snapshot.hasData){
           return Center(child: snapshot.length)
        } else return Container();
      },

//you can use too:
getData().then((listData){
      Center(child: listData)...
});

【讨论】:

  • 请问我在哪里用这个?
  • 请问我在哪里使用这个? @Norberto Martín Afonso
  • 在 Widget 构建中尝试(BuildContext 上下文){
猜你喜欢
  • 2021-06-25
  • 2022-12-12
  • 1970-01-01
  • 2021-08-22
  • 2021-01-13
  • 2020-07-29
  • 2014-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多