【问题标题】:flutter-firestore: how to count all elements in all arrays in a mapflutter-firestore:如何计算地图中所有数组中的所有元素
【发布时间】:2021-03-10 04:55:08
【问题描述】:

我正在尝试计算 firestore 映射内所有数组中的所有元素,以获得数字 3 的结果。

我使用下面的函数来获得计算chatRoomIds字段内所有元素的结果。

int _getUnseenMessagesNumber(List<Map<String, dynamic>> items) {
int counter = 0;
for (final item in items) {
  counter += item.values.first.length;
}
return counter;
}

最后我试着用下面的代码来显示计数的结果。

StreamBuilder<DocumentSnapshot>(
                      stream: FirebaseFirestore.instance
                          .collection('crews')
                          .doc(uid)
                          .snapshots(),
                      builder: (context, snapshot) {
                        int number = _getUnseenMessagesNumber(
                            snapshot.data['chatRoomIds']);
                        if (snapshot.data['chatRoomIds'] == null ||
                            number == 0) {
                          return null;
                        } else {
                          return Center(
                              child: Text(
                                number.toString(),
                          );
                        }
                      })

当我尝试上面的代码时,我收到一条错误消息type '_internalLinkedHashMap &lt;String, dynamic&gt; ' is not a subtype of type 'List&lt;Map&lt;String, dynamic&gt;&gt; '。 要解决什么问题才能避免此错误并获得我想要的结果?

【问题讨论】:

    标签: flutter dictionary google-cloud-firestore count


    【解决方案1】:

    我认为最好的解决方案是先构建一个模型,我使用 json serializable 来生成模型:

    import 'package:json_annotation/json_annotation.dart';
    
    part 'chat_rooms_ids_model.g.dart';
    
    @JsonSerializable()
    class ChatRoomsIds{
      List<PropertyOne> propertyOne;
      List<PropertyTwo> propertyTwo;
    ChatRoomsIds({this.propertyOne, this.propertyTwo});
     factory ChatRoomsIds.fromJson(Map<String, dynamic> json) =>
          _$ChatRoomsIdsFromJson(json);
      Map<String, dynamic> toJson() => _$ChatRoomsIdsToJson(this);
    }
    
    @JsonSerializable()
    class PropertyOne{
       String attributeOne;
    PropertyOne({this.attributeOne});
    factory PropertyOne.fromJson(Map<String, dynamic> json) =>
          _$PropertyOneFromJson(json);
      Map<String, dynamic> toJson() => _$PropertyOneToJson(this);
    }
    
    @JsonSerializable()
    class PropertyTwo{
       String attributeOne;
       String attributeTwo;
    PropertyOne({this.attributeOne, this. attributeTwo});
    factory PropertyTwo.fromJson(Map<String, dynamic> json) =>
          _$PropertyTwoFromJson(json);
      Map<String, dynamic> toJson() => _$PropertyTwoToJson(this);
    }
    

    这个模型你可以用命令自动生成:

    flutter pub run build_runner build --delete-conflicting-outputs
    

    现在,您可以在代码中实现模型,如下所示:

    StreamBuilder<DocumentSnapshot>(
                          stream: FirebaseFirestore.instance
                              .collection('crews')
                              .doc(uid)
                              .snapshots(),
                          builder: (context, snapshot) {
                           
                          if (snapshot.exists) {
                             var propertyOne = <PropertyOne>[];
                             (snapshot.data()['propertyOne'] as Map).forEach((_, value)){
      propertyOne.add(PropertyOne.fromJson(value));
    }
                              return Center(
                                  child: Text(
                                    propertyOne.first.attributeOne.toString(),
                              );
                            } else {
                              return null;
                            }
                          })
    

    【讨论】:

    • 谢谢victwise。我不明白代码、状态、细节……是什么意思。你能解释一下我的案例的模型吗?我有一个字段名称“chatRoomIds”和里面的数组。
    • 对不起,我应该更具体一些。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    相关资源
    最近更新 更多