简体   繁体   中英

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:

在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM