flutter - 使用 FutureBuilder 我在快照上获取空数据,而不是在构建器函数中获取数据
问题描述
// getActivityFeed() function
class _ActivityFeedState extends State<ActivityFeed> {
Future<List<ActivityFeedItem>> getActivityFeed() async {
QuerySnapshot snapshot = await activityFeedRef
.doc(currentUser.id)
.collection('feedItems')
.orderBy('timestamp', descending: true)
.limit(50)
.get();
print(snapshot.docs);
snapshot.docs.forEach((doc) {
print(doc.data());
List<ActivityFeedItem> feedItems = [];
feedItems.add(ActivityFeedItem.fromDocument(doc));
print(feedItems);
// print('Activity Feed Item: ${doc.data}');
});
print("feed2: $feedItems");
return feedItems;
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.orange,
appBar: header(context, titleText: "Activity Feed"),
body: Container(
child: FutureBuilder(
future: getActivityFeed(),
builder: (context, snapshot) {
print("hey$feedItems");
if (!snapshot.hasData) {
return circularProgress();
}
return ListView(
children: snapshot.data,
);
},
)),
);
}
}
//FutureBuilder
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.orange,
appBar: header(context,
titleText: "Activity Feed",
),
body: Container(
child: FutureBuilder(
future: getActivityFeed(),
builder: (context, snapshot) {
print("hey$feedItems");
if (!snapshot.hasData) {
return circularProgress();
}
return ListView(
children: snapshot.data,
);
},
),
),
);
}
}
我没有得到快照数据....快照数据为空,未来的构建器返回我循环Progess()......我已经定义了函数getActivityFeed,它是一个未来。我可以在调试控制台中看到有快照数据并且可以在控制台中看到 snapshot.doc 数据,但不知何故 print(doc.data()) 之后的代码没有执行并且 print(feedItems) 我在控制台中看不到它。我在代码中做错了什么?
解决方案
您正在为每个初始化列表。
snapshot.docs.forEach((doc) {
List<ActivityFeedItem> feedItems = []; // This line
feedItems.add(ActivityFeedItem.fromDocument(doc));
});
将此行移到 forEach 之外
List<ActivityFeedItem> feedItems = [];
snapshot.docs.forEach((doc) {
feedItems.add(ActivityFeedItem.fromDocument(doc));
});
推荐阅读
- c++ - 运行dijkstra算法的问题
- javascript - 如何恢复默认事件侦听器以提交表单
- c - Leetcode:AddressSanitizer 堆缓冲区溢出
- r - 如何在数据框中找到与给定向量最相似的行
- ios - 如果我在 IOS Swift 上有地点坐标信息,我们如何检索 PlaceID
- ios - Google OAuth 登录:iOS 应用程序中的 redirect_uri_mismatch 错误
- html - 无法在最大宽度为 375px 的移动设计上隐藏 SVG 图形的溢出
- python - 为什么使用 __init__(self, **kwargs) 返回以下错误代码:SyntaxError: invalid syntax?
- c++ - strchr函数内的Valgrind memcheck错误
- clojure - 尝试从文本文件中读取数据并填充整数列表