android - 颤振嵌套的火力基地
问题描述
有人能解释一下为什么这个类运行时 productlist 变量为空吗?看起来变量是在第一个实例结束后填充的,因此 CardShopList 小部件没有来自嵌套实例的产品列表。你有什么建议吗?谢谢!
Future getMyShopLists(User user) async {
List<Widget> listItems = [];
FirebaseFirestore.instance
.collection('user')
.doc(user.uid)
.collection('shoplist')
.get()
.then((event) {
event.docs.forEach((shoplist) {
List<ProductModel> productlist = [];
Map shopListData = shoplist.data();
shoplist.reference.collection('productlist').get().then((element) {
Map productData = shoplist.data();
element.docs.forEach((doc) {
productlist.add(ProductModel(
id: doc.id,
name: productData['name'],
quantity: productData['quantity'],
price: productData['price'],
));
});
});
listItems.add(CardShopList(
shoplist.id,
shopListData['name'],
productlist, // <------------------------------- THIS IS NULL!!!!
getMyShopLists,
key: ValueKey<String>(shoplist.id),
));
});
if (this.mounted) {
setState(() {
shopListsWidget = listItems;
});
}
});
return shopListsWidget;
}
编辑我在这个 FutureBuilder 中使用该类:
FutureBuilder(
future:
searchIcon.icon == Icons.search ? getMyShopLists(user) : null,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return isShopListEmpty
? new Center(
child: new Text(
"x",
style: TextStyle(fontSize: 20),
textAlign: TextAlign.center,
),
)
: Container(
child: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: shopListsWidget.length,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return shopListsWidget[index];
}))
],
),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
解决方案
由于您使用的是 foreach,因此预计不会填写“产品列表”。可能有替代解决方案,但将 foreach 转向 for 可能会解决它。
...
await FirebaseFirestore.instance //added await
.collection('user')
.doc(user.uid)
.collection('shoplist')
.get()
.then((event) async{ //added async
for(QueryDocumentSnapshot shoplist in event.docs){ //---this line changed
List<ProductModel> productlist = [];
Map shopListData = shoplist.data();
await shoplist.reference.collection('productlist').get().then((element) //added await
{
Map productData = shoplist.data();
for(QueryDocumentSnapshot doc in element.docs) //---this line changed
{
productlist.add(ProductModel(
id: doc.id,
name: productData['name'],
quantity: productData['quantity'],
price: productData['price'],
));
}
});
listItems.add(CardShopList(
shoplist.id,
shopListData['name'],
productlist,
getMyShopLists,
key: ValueKey<String>(shoplist.id),
));
}
...
推荐阅读
- c++ - Srand 正在输出一个巨大的数字列表,而不仅仅是一个
- database - Postgres 转储数据库
- python - 如何简单地编码和编码字典问题的重复性
- php - 无法访问对象中的日期值
- python - Keras iterator with augmented images and other features
- excel - Excel VBA 中的 TAB 事件问题
- python - AttributeError:“input_4”层有多个入站节点,输出形状不同
- java - 构造函数参数中 List 的空指针异常
- python - 为什么 django 在制作我的第一个投票应用程序时给我这个错误
- c# - 如何从另一个类 C#/MVC 访问属性