首页 > 解决方案 > Error when getting data from StreamBuilder BloC firestore Flutter

问题描述

I have been having problems with my APP in Flutter... I tried to get data from Bloc and Repositore and Firestore and it displays in my GridView, but get this error:

enter image description here

My UI Code:

Widget bodyGallery2() => SafeArea(
    child: Scaffold(
      body: Stack(
        children: <Widget>[
          StreamBuilder<List<PhotoDish>>(
            stream: _dishBloc.streamPhotoDish,
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return CircularProgressIndicator();
              }
              print(snapshot.toString());
              return GridView.count(
              crossAxisCount: 1,
              crossAxisSpacing: 4.0,
              mainAxisSpacing: 8.0,
              childAspectRatio: 3/2,
              children: snapshot.data
                    .map((photo)=>buildItemPhoto(photo)),
              );
            }
      )
        ]
    ),
    ),
  );

  Widget buildItemPhoto(PhotoDish listphoto){
    return Text(listphoto.idDish+":::PhotoDish");
  }

My Bloc Code, it has the Stream to list of PhotoDish from my Repo:

class DishBloc extends Bloc{ 
  RepositoryFirestore _repository = RepositoryFirestore();

  PhotoDishRepo _repo = FirestoreDishProvider();
  Stream<List<PhotoDish>> get streamPhotoDish => _repo.streamPhotoDish;

My Repo Code has the call to get data from firebase and it set in StreamController:

abstract class PhotoDishRepo {
  Stream<List<PhotoDish>> get streamPhotoDish;
}
class FirestoreDishProvider implements PhotoDishRepo{
  StreamController<List<PhotoDish>> _streamController = BehaviorSubject<List<PhotoDish>>();

  Firestore _firestore = Firestore.instance;
  List<PhotoDish> _listPhotoDish = List();

  FirestoreDishProvider() {

    _firestore
      .collection(Constants.namePhotoDishCollection) 
      .snapshots()
      .listen((QuerySnapshot snapshot){
        snapshot.documents.forEach((obj){
          _listPhotoDish.add(PhotoDish(
            date: DateTime.now(),
            id: obj.data["id"],
            idDish: obj.data["idDish"],
            idUser: obj.data["idUser"],
            photo: obj.data["photo"],
          ));
        });

print("TOTALL:::"+_listPhotoDish.length.toString());
        _streamController.add(_listPhotoDish);
      });
  }

标签: firebaseflutterblocstream-builder

解决方案


I think you are just miss to add .ToList() method at the end where you are mapping list into widget.

Map only convert your data into widget, which return single widget while gridview children argument require list of widgets, so you have to covert it into list.

children: snapshot.data
                    .map((photo)=>buildItemPhoto(photo)).toList(), //convert to list
              );

推荐阅读