flutter - 颤振显示在 null 上调用了方法“[]”。在列表生成器上
问题描述
我正在从 api 获取数据并在 ListView 构建器中显示但它显示错误
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
bool show = false;
var map = {};
@override
void initState() {
dosomestuff();
}
Future<List> dosomestuff() async {
http.Response res = await http.get(
'http://retailapi.airtechsolutions.pk/api/menu/2112',
);
Map<String, dynamic> map = json.decode(res.body);
if (map['description'] == "Success") {
print('show kr ');
print(map["Categories"].length);
print(map["Categories"]);
setState(() {
show = true;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: show
? ListView.builder(
itemCount: map["Categories"].length,
scrollDirection: Axis.horizontal,
shrinkWrap: true,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return Container(
width: 80.0,
child: Text(map["Categories"][index]['Name'])
);
},
) : Container(),
);
}
}
它的显示错误The method '[]' was called on null
。但是当我在状态函数中打印值时,它的打印值和所有东西都在工作,但是当在 ListBuilder 中显示错误时,它会显示该错误。
你可以看到我打印函数中的值
print(map["Categories"].length);
print(map["Categories"]);
它的印刷价值一切都很好。
您可以在图像中看到它打印的长度和数组很好,所以当我在小部件中使用它说长度被调用时它不为空 -_-
解决方案
你能试试这个吗?我可能打错了括号。
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
bool show = false;
var map = {};
List<dynamic> getCategory;
@override
void initState() {
dosomestuff();
}
Future<List> dosomestuff() async {
await http.get(
'http://retailapi.airtechsolutions.pk/api/menu/2112',
).then((result){
http.Response res=result;
Map<String, dynamic> map = json.decode(res.body);
if (map['description'] == "Success") {
if(map["Categories"].length>0){
setState(() {
show = true;
getCategory=map["Categories"];
});
}
}
}
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: show
? ListView.builder(
itemCount: getCategory.length,
scrollDirection: Axis.horizontal,
shrinkWrap: true,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return Container(
width: 80.0,
child: Text(getCategory[index]['Name'])
);
},
) : Container(),
);
}
}
推荐阅读
- python - 如何运行托管在 a2hosting 上的 Flask 应用程序?
- matlab - 如何优化此字符串替换代码
- angular7 - 两种语言 Angular 构建,一种正常,一种有错误
- c# - C# - 线程任务 - Dotnet 4.x 中的最佳实践
- nix - 如何将我的 nix 环境重置为原始用户配置文件?
- c# - MailAddress 到正确的传真服务器工作不正常
- reactjs - 如何在reactjs的组件中使用存储在另一个constant.js文件中的数组
- php - 如何将phpdom保存到xml中?
- google-apps-script - 范围宽度不正确(为 1 但应为 2)
- hadoop - 如何为映射器输出设置 avro 压缩编解码器?