0

我正在尝试从 Firestore 获取数据并使用流将该数据传递到屏幕。我已经使用 完成了此操作FutureBuilder,此解决方案的工作原理如下,但我需要使用StreamBuilder谁能帮我找到问题?

Future<List<Business>> list(FirebaseFirestore _firesore) async {
    CollectionReference _col = _firesore.collection('Buisiness');
    var _result = await _col.get();
    var _docs =  _result.docs;
    return List.generate(_docs.length, (index) {
      var satir = _docs[index].data();
      return Business.fromMap(satir as Map<String, dynamic>);
    });
  }

此代码适用于 FutureBuilder 但不适用于 StreamBuilder

 StreamBuilder<List<Business>>(
          stream: _firestorelist.list(_firestore), // Error Here
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              List<Business>? data = snapshot.data;
              return ListView.builder(
                itemCount: data!.length,
                itemBuilder: (context, index) {
                  var result = data[index];
                  return ListTile(
                    title: Text(result.nereden),
                    subtitle: Text(result.nereye),
                    trailing: Text(result.fiyat),
                  );
                },
              );
            } else {
              return CircularProgressIndicator();
            }
          },
        )```
4

2 回答 2

0

当前方法是一个One-time Read方法,可以从特定的集合中获取快照。

您可以像这样更改方法,然后将其用作流streamBuilder

list(FirebaseFirestore _firesore) async {
    CollectionReference _col = _firesore.collection('Buisiness');
    var _result = await _col.snapshots();
    return _result;
  }
于 2022-02-13T05:43:52.733 回答
0

您可以将数据源方法编写为

Stream<List<Business>> list(FirebaseFirestore _firesore) {
  CollectionReference _col = _firesore.collection('Buisiness');

  final _snap = _col.snapshots();

  return _snap.map((event) => event.docs
      .map<Business>((e) => Business.fromMap(e.data() as Map<String, dynamic>))
      .toList());
}
于 2022-02-13T05:44:58.017 回答