【问题标题】:Read List Stream and show on List View Firebase Flutter读取 List Stream 并在 List View Firebase Flutter 上显示
【发布时间】:2021-04-24 19:45:36
【问题描述】:

我已经为此苦苦挣扎了好几天:

      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&lt;List&lt;DocumentSnapshot&gt;&gt; 流的结果。

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

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

【问题讨论】:

    标签: firebase flutter google-cloud-firestore stream


    【解决方案1】:

    我可以通过从流中创建一个列表,然后将该列表与 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"]);
             );
          }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-07
      • 2021-05-17
      • 2023-01-25
      • 2021-12-21
      • 2020-10-03
      • 2020-06-01
      • 2021-11-11
      • 2021-06-01
      相关资源
      最近更新 更多