我正在尝试从Firecloud数据库获取描述文本,并在3个不同的小部件中使用它们,将这些小部件添加到列表中,然后将该列表传递给ListView
。
为此,我在StreamBuilder
中执行了以下代码:
StreamBuilder(
stream: FirebaseFirestore.instance.collection('humansOfLpc').snapshots(),
builder: (BuildContext context,snapshot){
if(!snapshot.hasData){
return Center(
child: Text('Loading...'),
);
}
print('outside title and desc widget');
List<TitleAndDescription> titleAndDescriptions=[
];
snapshot.data.docs.map((document){
final about = document.data()["about"];
final aftercampusProgress =document.data()["afterCampusPlacement"];
final incampusPlacement = document.data()["incampusProgress"];
print('inside snapshots');
print(about);
final aboutDesc = TitleAndDescription(
title: 'About',
description: about,
);
final incampusProgressDesc = TitleAndDescription(
title: 'In-Campus Progress',
description: incampusProgress,
);
final afterCampusPlacementDesc=TitleAndDescription(
title: 'After Campus Placements',
description: afterCampusPlacement,
);
titleAndDescriptions.add(aboutDesc);
titleAndDescriptions.add(incampusProgressDesc);
titleAndDescriptions.add(afterCampusPlacementDesc);
});
return Expanded(
child: ListView(
children: titleAndDescriptions,
),
);
},
),
我在这里面临的主要问题是它不读取以下代码:snapshot.data.docs.map((document){
final about = document.data()["about"];
final aftercampusProgress =document.data()["afterCampusPlacement"];
final incampusPlacement = document.data()["incampusProgress"];
print('inside snapshots');
print(about);
final aboutDesc = TitleAndDescription(
title: 'About',
description: about,
);
final incampusProgressDesc = TitleAndDescription(
title: 'In-Campus Progress',
description: incampusProgress,
);
final afterCampusPlacementDesc=TitleAndDescription(
title: 'After Campus Placements',
description: afterCampusPlacement,
);
titleAndDescriptions.add(aboutDesc);
titleAndDescriptions.add(incampusProgressDesc);
titleAndDescriptions.add(afterCampusPlacementDesc);
});
我可以这样说,因为控制台正在打印'outside title and desc widget'
,但没有打印'inside snapshots'
。因此,我的
titleAndDescriptions
列表为空,并且我的UI上没有3个小部件以及数据。请告诉我我做错了什么,我有什么选择呢?提前致谢。
最佳答案
使用forEach
而不是map
snapshot.data.docs.forEach((document){
final about = document.data()["about"];
final aftercampusProgress =document.data()["afterCampusPlacement"];
final incampusPlacement = document.data()["incampusProgress"];
print('inside snapshots');
print(about);
final aboutDesc = TitleAndDescription(
title: 'About',
description: about,
);
final incampusProgressDesc = TitleAndDescription(
title: 'In-Campus Progress',
description: incampusProgress,
);
final afterCampusPlacementDesc=TitleAndDescription(
title: 'After Campus Placements',
description: afterCampusPlacement,
);
titleAndDescriptions.add(aboutDesc);
titleAndDescriptions.add(incampusProgressDesc);
titleAndDescriptions.add(afterCampusPlacementDesc);
});
在此处查看Why map doesn't work but forEach does。关于firebase - 在Flutter中从Firebase FireCloud接收数据时,不会执行StreamBuilder中的快照代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63748354/