简体   繁体   中英

Flutter Stream Builder with Firestore return empty list

Hey I tried to get data from firestore, the data is there, but the stream return empty list, any help will be appreciated!

Here is my stream builder code:

StreamBuilder<List<ChatModel>>(
            stream: ChatRoom.getChats(id),
            builder: (context, snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                default:
                  if (snapshot.hasError) {
                    print(snapshot.error);
                    return Center(
                        child: Text('Something Went Wrong Try later'));
                  } else {
                    if (snapshot.hasData) {
                      final message = snapshot.data;
                      print(message);
                      return ListView.separated(
                          itemBuilder: (context, index) => messageWidget(
                              message![index].message,
                              message![index].source == _userId),
                          separatorBuilder: (context, index) => SizedBox(
                              height: SizeConfig.safeBlockVertical * 3),
                          itemCount: snapshot.data!.length);
                    } else
                      return Center(child: Text('Say Hi..'));
                  }
              }
            }),

here is how I call the firestore:

class ChatRoom {
  String id;
  ChatRoom({required this.id});

  static Stream<List<ChatModel>> getChats(String id) =>
    FirebaseFirestore.instance
      .collection(id)
      .orderBy(ChatField.sendAt, descending: false)
      .snapshots()
      .transform(Util.transformer(ChatModel.fromJson));
}

and here is how I transform the data:

static StreamTransformer<QuerySnapshot<Map<String, dynamic>>, List<T>> transformer<T>(
  T Function(Map<String, dynamic> json) fromJson) =>
  StreamTransformer<QuerySnapshot<Map<String, dynamic>>, List<T>>.fromHandlers(
    handleData: (QuerySnapshot data, EventSink<List<T>> sink) {
      final snaps = data.docs.map((doc) => doc.data()).toList();
      final object = snaps.map((json) => fromJson(json as Map<String, dynamic>)).toList();

      sink.add(object);
    },
  );

here is the model

static ChatModel fromJson(Map<String, dynamic> json) => ChatModel(
  dest: json["dest"],
  destName: json['destName'],
  id: json['id'],
  message: json["message"],
  sendAt: json["sendAt"],
  source: json["source"],
  sourceName: json["sourceName"],
);

here is the screenshot of the firestore: 在此处输入图像描述

Hello You have to check snapshot data if its null or not please see below code hope this works for you

StreamBuilder<List<ChatModel>>(
            stream: ChatRoom.getChats(id),
            builder: (context, snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                default:
                  if (snapshot.hasError) {
                    print(snapshot.error);
                    return Center(
                        child: Text('Something Went Wrong Try later'));
                  } else {
                    if(snapshot.data != null){
                    final message = snapshot.data;
                        return snapshot.data.size > 0 ?

                      print(message);
                     ListView.separated(
                          itemBuilder: (context, index) => messageWidget(
                              message![index].message,
                              message![index].source == _userId),
                          separatorBuilder: (context, index) => SizedBox(
                              height: SizeConfig.safeBlockVertical * 3),
                          itemCount: snapshot.data!.size) : 
                     Center(child: Text('Say Hi..'));
                    }
                    return Center(child: Text('Say Hi..'));

              }
            }),

Let me know if it's work.

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