首页 > 解决方案 > 读取 List Stream 并在 List View Firebase Flutter 上显示

问题描述

我现在为此苦苦挣扎了好几天:

      static Future<List<Job>> getJobs() async {
double lat = await MySharedPreferences.instance.getDoubleValue('lat');
print(lat);
double long = await MySharedPreferences.instance.getDoubleValue('long');
print(long);

GeoFirePoint center = geo.point(latitude: lat, longitude: long);
var collectionReference = _firestore.collection('Job_data');

Stream<List<DocumentSnapshot>> stream = geo
    .collection(collectionRef: collectionReference)
    .within(center: center, radius: 50, field: 'position');
stream.listen((List<DocumentSnapshot> snapshot) {
  for (int i = 0; i < snapshot.length; i++) {
    jobtype.add(snapshot[i].data()['type']);
    print(jobtype[i]);
  }
});
   }
    }

    class BodyLayout extends StatelessWidget {
@override
Widget build(BuildContext context) {
return _myListView(context);
}
}

Widget _myListView(BuildContext context) {
return ListView.builder(
  itemCount: jobtype.length,
  itemBuilder: (context, index) {
    return ListTile(title: Text(jobtype[index]));
  });
}

我想Stream<List<DocumentSnapshot>>在我的列表视图中显示流的结果。

如果我打印print(jobtype[i]);,我会看到来自 firebase 的所需值,但到目前为止我还没有找到将这些值添加到列表视图的有效解决方案。我想我需要一个Streambuilder,但它不适用于我StreamList。不幸的是 GeoFlutterFire 只返回StreamList

有人可以告诉我如何在列表视图中正确显示这些值吗?使用我当前的“解决方案”,它会在我的列表视图中显示值,但它们是双倍的并且没有正确加载。

标签: firebasefluttergoogle-cloud-firestorestream

解决方案


我能够通过从流中创建一个列表,然后将该列表与 ListView.builder 一起使用来使其工作

List<DocumentSnapshot> _newList = [];

Stream<List<DocumentSnapshot>> stream = geo
    .collection(collectionRef: collectionReference)
    .within(center: center, radius: 50, field: 'position');
stream.listen((List<DocumentSnapshot> snapshot) {

    if (snapshot.length > 0){
       _newList = snapshot;
    }

});
.
.
.
.
ListView.builder(
     itemCount: _newList.length,
     itemBuilder: (BuildContext ctx, int index) {
        return ListTile(
           title: Text(_newList[index].data["name"]);
         );
      }
)

推荐阅读