Home > OS >  How can I convert FutureBuilder code to StreamBuilder?
How can I convert FutureBuilder code to StreamBuilder?

Time:02-13

I am trying to get data from Firestore and pass that data to screen using stream. I have done this using FutureBuilder, this solution works as followed, but I need to use StreamBuilder Can anyone help me find the problem?

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

This Code works in FutureBuilder but not 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();
            }
          },
        )```

CodePudding user response:

You can write your data source method as

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

CodePudding user response:

The current method is a One-time Read method, You can get snapshots from the specific collection.

You can change the method like this and Then use it as stream in streamBuilder:

list(FirebaseFirestore _firesore) async {
    CollectionReference _col = _firesore.collection('Buisiness');
    var _result = await _col.snapshots();
    return _result;
  }
  • Related