How can I convert FutureBuilder code to StreamBuilder?

Issue

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

Solution

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

Answered By – Khadga shrestha

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *