【问题标题】:Create a list of models from a list of data from documents从文档中的数据列表创建模型列表
【发布时间】:2021-12-29 01:27:32
【问题描述】:

我的 Flutter 应用将接收来自用户的帖子。我的 swift 应用程序在我的 firebase firestore 数据库中有要替换的帖子。所以因为我在我的颤振获取帖子功能中有这个:

    final userRef = FirebaseFirestore.instance.collection('users');

        final QuerySnapshot result = await userRef.get();

        result.docs.forEach((res) async {
          print(res.id);
          QuerySnapshot posts = await userRef.doc(res.id).collection("posts").get();

          posts.docs.forEach((res) {
            print(res.data());
          });
        });

因此,使用此功能,我可以打印每个用户发布的所有数据的列表。这是印刷品的一部分:

flutter: {postedDate: Oct 24, 2021 at 6:10 AM, id: twentyonepilots_354_1635073829.595439, caption: , likers: [], postUrlString: https://firebasestorage.googleapis.com:443/v0/b/globe-e8b7f.appspot.com/o/twentyonepilots%2Fposts%2Ftwentyonepilots_354_1635073829.595439.png?alt=media&token=48b6b1bc-112b-4d61-84ee-3847ba8dce94}
flutter: {postedDate: 13 Aug 2021, 9:54 AM, id: viktoria_923_1628837663.179892, caption: just posted, feeling good :), likers: [anelia, globetester, alis, devil, vladyynk, fllcuriie, HackerX, nihilistic, imherefromtiktok, donnasmithofficial, hhhh, sachiq], postUrlString: https://firebasestorage.googleapis.com:443/v0/b/globe-e8b7f.appspot.com/o/viktoria%2Fposts%2Fviktoria_923_1628837663.179892.png?alt=media&token=634ff70e-028c-4452-8c2b-b598eb8b8e48}
flutter: {postedDate: 21. Nov 2021 at 18:34, id: timsbs_464_1637516088.259705, caption: Hi https://google.com, likers: [timsbs], postUrlString: https://firebasestorage.googleapis.com:443/v0/b/globe-e8b7f.appspot.com/o/timsbs%2Fposts%2Ftimsbs_464_1637516088.259705.png?alt=media&token=4ce3bf4d-3187-4ee9-954a-dc39532694ae}

我怎样才能把这个列表变成这个帖子模型的列表?:

class Post {
  String id = "";
  String caption = "";
  String postUrlString = "";
  Timestamp postedDate = Timestamp.now();

  Post(
      {required this.id,
      required this.caption,
      required this.postUrlString,
      required this.postedDate});
}

【问题讨论】:

    标签: flutter google-cloud-firestore


    【解决方案1】:

    向 Post 类添加一个 'fromJson' 方法,如下所示。

          final userRef = FirebaseFirestore.instance.collection('users');
    
          final QuerySnapshot result = await userRef.get();
    
          List<Post> listPosts = [];
    
          result.docs.forEach((res) async {
            print(res.id);
            QuerySnapshot posts = await userRef.doc(res.id).collection("posts").get();
    
            posts.docs.forEach((res) {
              listPosts.add(Post.fromJson(res.data() as Map<String, dynamic>));
            });
    
            print(listPosts);
          });
    
    class Post {
      final String id;
      final String caption;
      final String postUrlString;
      final Timestamp postedDate;
    
      Post(
          {required this.id,
          required this.caption,
          required this.postUrlString,
          required this.postedDate});
      
      Post.fromJson(Map<String, dynamic> json)
        : id = json['id'],
          caption = json['caption'],
          postUrlString = json['postUrlString'],
          postedDate = json['postedDate'] != null ? Timestamp.fromDate(json['postedData']) : Timestamp.now();
    
      @override
      String toString() => '''Post { id: $id,
         caption: $caption,
         postUrlString: $postUrlString
         postedData: $postedData
      }''';
    }
    

    【讨论】:

    • 我添加了 'as Map' 转换代码。使用更改的代码重试
    • 谢谢,现在没有错误,但是当我使用此代码并打印 listPosts 时,我只会打印很多次 #1 DatabaseManager.fetchPosts.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (package:globe_flutter/services/database.dart:26:30) #2 List.forEach (dart:core-patch/growable_array.dart:410:8) #3 DatabaseManager.fetchPosts.&lt;anonymous closure&gt; (package:globe_flutter/services/database.dart:24:20) &lt;asynchronous suspension&gt;(每个帖子一次)。我不确定这是否意味着代码不起作用,或者列表只是不可打印。
    • 你会用注释掉“另一种方式”的代码再试一次吗?
    • 用另一种方式,当打印listPosts 我得到这个打印... [VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'DateTime' #0 new Post.fromJson (package:globe_flutter/models/post.dart:32:45) #1 DatabaseManager.fetchPosts.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (package:globe_flutter/services/database.dart:29:61) #2 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31) #3 ListIterator.moveNext (dart:_internal/iterable.dart:342:26) (其余的下一条评论)
    • #4 new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:188:27) #5 new _GrowableList.of (dart:core-patch/growable_array.dart:150:28) #6 new List.of (dart:core-patch/array_patch.dart:51:28) #7 ListIterable.toList (dart:_internal/iterable.dart:213:44) #8 DatabaseManager.fetchPosts.&lt;anonymous closure&gt; (package:globe_flutter/services/database.dart:29:107) &lt;asynchronous suspension&gt;
    猜你喜欢
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多