首页 > 解决方案 > 使用 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) 我在控制台中看不到它。我在代码中做错了什么?

标签: fluttersnapshotflutter-futurebuilder

解决方案


您正在为每个初始化列表。

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));
});

推荐阅读