简体   繁体   English

Flutter 使用 Stream 检索 firestore 集合

[英]Flutter Retrieving firestore collection using Stream

I am trying to retrieve a whole collection in firestore using StreamBuilder but I got stuck in mapping the result according to my dart model我正在尝试使用StreamBuilderfirestore中检索整个集合,但我无法根据我的 dart model 映射结果

This is the dart model thread.dart:这是 dart model thread.dart:

class Thread {
  final String threadTitle;
  final String threadContent;
  final String threadFlair;
  final String threadTimestamp;
  final List<String> threadLikedBy;
  final List<String> originalPoster;

  Thread({
    this.threadTitle,
    this.threadContent,
    this.threadTimestamp,
    this.threadFlair,
    this.threadLikedBy,
    this.originalPoster,
  });

  factory Thread.fromMap(Map<String, dynamic> map) => Thread(
    threadTitle: map["threadTitle"],
    threadContent: map["threadContent"],
    threadFlair: map["threadFlair"],
    threadTimestamp: map["threadTimestamp"],
    threadLikedBy: List<String>.from(map["threadLikedBy"].map((x) => x)),
    originalPoster: List<String>.from(map["originalPoster"].map((x) => x)),
  );

  Map<String, dynamic> toMap() => {
    "threadTitle": threadTitle,
    "threadContent": threadContent,
    "threadFlair": threadFlair,
    "threadTimestamp": threadTimestamp,
    "threadLikedBy": List<dynamic>.from(threadLikedBy.map((x) => x)),
    "originalPoster": List<dynamic>.from(originalPoster.map((x) => x)),
  };
}

This is the widget where I display the results in a listview:这是我在列表视图中显示结果的小部件:

class _ThreadsBodyState extends State<ThreadsBody> {
  final threads = _mThreadService.retriveData(path: "posts", builder: (data) => Thread.fromMap(data));
  @override
  Widget build(BuildContext context) {
    return Container(
      child: StreamBuilder<Object>(
        stream: threads,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                Thread thrd = (snapshot.data as List)[index];
                return ThreadCard(thread: thrd,);
              },
            );
           } else {return Text('no data');}
      }),
    );
  }
}

and here's posts_service.dart where I have the Stream function这是 posts_service.dart 我有 Stream function

//After restructuring my model and adding: 
//List<String> threadLikedBy; and List<String> originalPoster;
//this method works no more

Stream<List<T>> retrieveData<T>({
  @required String path,
  @required T builder(Map<String, dynamic> data),
}) {
  final reference = firestoreInstance.collection(path);
  final snapshots = reference.snapshots();
  return snapshots.map((snapshot) => snapshot.docs.map((snapshot) => builder(snapshot.data())).toList());
}

It appears to be that I am messing up the mapping in the return but I can't exactly figure out how to fix it.看来我在返回中弄乱了映射,但我无法确切地弄清楚如何修复它。

in your 'posts_services.dart' add the following function:在您的“posts_services.dart”中添加以下 function:

Future<QuerySnapshot> fetchThreads() async {
    return await firestoreInstance.collection('posts').get();
}

Now in your widget where you build your ListView should look like this:现在在您构建ListView的小部件中应该如下所示:

class _ThreadsBodyState extends State<ThreadsBody> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder<QuerySnapshot>(
        future: youService.fetchThreads(),
        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data.size, //to retrieve the size
              itemBuilder: (BuildContext context, int index) {
                Thread thrd = Thread.fromMap(snapshot.data.docs[index].data());
                return ThreadCard(thread: thrd,);
              },
            );
           } else {return Text('no data');}
      }),
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Firestore 集合查询为 flutter 中的 stream - Firestore collection query as stream in flutter 如何在 flutter stream 生成器中使用不同的 firestore 集合创建 where 条件? - How to make where condition with different firestore collection in flutter stream builder? Stream 构建器在使用 Firestore 发布的 flutter 应用程序上返回 null - Stream builder returns null on released flutter app using firestore Flutter/Firestore 返回类型列表<review>不是类型“Map”的子类型<string, dynamic> ' 从 Stream 检索快照时</string,></review> - Flutter/Firestore returns type List<Review> is not a subtype of type 'Map<String, dynamic>' when retrieving snapshots from Stream Flutter Firebase - 在具有多个文档的集合中使用 where 检索数据 - Flutter Firebase - retrieving data using where in a collection with multiple docs 如何使用 flutter 从 Firestore 获取子集合? - How do I fetch sub collection from firestore using flutter? Stream builder 从 firestore 到 flutter - Stream builder from firestore to flutter 在 flutter 中获取 Firestore 集合时出现问题 - Problem getting Firestore collection in flutter 在 Flutter 中从 Firestore 检索和投射单个文档 - Retrieving and casting single document from Firestore in Flutter 使用 Stream 检索数据<querysnapshot>在 Firebase 和 Flutter</querysnapshot> - Retrieving Data with Stream<QuerySnapshot> in Firebase with Flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM