我是新手,每次运行应用程序时都会出错:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building DataList(dirty, dependencies:
[_InheritedProviderScope<List<Store>>], state: _DataListState#67e37):
The getter 'length' was called on null.
Receiver: null
Tried calling: length
The relevant error-causing widget was:
DataList
这是我的数据列表文件:
class DataList extends StatefulWidget {
@override
_DataListState createState() => _DataListState();
}
class _DataListState extends State<DataList> {
@override
Widget build(BuildContext context) {
final stores = Provider.of<List<Store>>(context);
// stores.forEach((d) {
// print(d.name);
// });
return ListView.builder(
itemCount: stores.length,
itemBuilder: (context, index) {
return StoreTile(store: stores[index]);
},
);
}
}
这是在我登录并显示商店列表之后发生的。
我已经打印了stores.length
,它返回6,但是由于某种原因,应用程序发现了null
并抛出错误。
请注意,应用程序上的屏幕显示正确,但是在调试控制台中却出现此错误。
感谢您的帮助 乔
答案 0 :(得分:1)
您的提供商有一些时间来获取数据,请在此之前使用CircularProgressIndicator
stores.length >0 ? ListView.builder(
itemCount: stores.length,
itemBuilder: (context, index) {
return StoreTile(store: stores[index]);
},
) : CircularProgressIndicator();
答案 1 :(得分:1)
似乎您的提供者花了一些时间来获取商店列表,因此stores
暂时为空。您可以在stores
为空时显示进度指示器,然后再显示数据
class _DataListState extends State<DataList> {
@override
Widget build(BuildContext context) {
final stores = Provider.of<List<Store>>(context);
// stores.forEach((d) {
// print(d.name);
// });
return stores == null
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: stores.length,
itemBuilder: (context, index) {
return StoreTile(store: stores[index]);
},
);
}
}