firebase - 如何为Map <String,dynamic>类型的映射添加值?

标签 firebase flutter dart

这张 map 记录了谁发表了帖子,谁未发表。该字符串存储用户标识,该值是一个 bool(boolean) 值,表示他是否对该帖子进行了投票。我最初使用Map ,但出现错误,提示“InternalLinkedHashMap 不是Map 的子类型。因此,我将值从 bool(boolean) 类型更改为动态。但是,以下代码似乎不适用于动态类型。如何更改代码并将 bool(boolean) 型初始化为带有动态类型的false?

@override
  void initState() {
    super.initState();
    Firestore.instance.collection('public').document('internship_experiences').collection('Experiences')
    .document(widget.experience.documentid).get().then((value) async {
      final uid = await Provider.of(context).auth.getCurrentUID();

    if (value.data['saved'] == null
      ||value.data['upvotes'] == null || value.data['saved'][uid] == null || value.data['upvotes'][uid] == null) {

      widget.experience.saved.putIfAbsent(uid, () => false);
      widget.experience.upvotes.putIfAbsent(uid, () => false);

      Firestore.instance.collection('public').document('internship_experiences').collection('Experiences')
      .document(widget.experience.documentid).setData({
        'saved': widget.experience.saved,
        'upvotes': widget.experience.upvotes,
      }, merge: true).then((_){
        print("success at null!");
        });
      } else {
        setState(() {
          isSaved = value.data['saved'][uid]; //accessing value 
          isUpvoted = value.data['upvotes'][uid];
        });
       print('set state upon opening page');
      }
    });
  }


class Experience {
  String title;
  String company; 
  String role;
  String timePeriod; 
  String content; 
  String timestamp;
  String username;
  String profilePicture;
  String documentid;
  String ownerid;
  Map<String, dynamic> saved = {};
  Map<String, dynamic> upvotes = {};
  

  Experience(
    this.title,
    this.timePeriod,
    this.role,
    this.content,
    this.timestamp,
    this.company,
    this.username,
    this.profilePicture,
    this.documentid,
    this.ownerid,
    this.saved,
    this.upvotes,
  );

  Experience.fromSnapshot(DocumentSnapshot snapshot) : 
  title = snapshot["title"],
  content = snapshot['content'],
  timestamp = snapshot['timestamp'],
  role = snapshot['role'],
  username = snapshot['username'],
  profilePicture = snapshot['profilePicture'],
  documentid = snapshot['documentid'],
  timePeriod = snapshot['timePeriod'],
  ownerid = snapshot['ownerid'],
  company = snapshot['company'],
  upvotes = snapshot['upvotes'],
  saved = snapshot['saved'];
}

最佳答案

首先,您可以通过将Map<String, bool>值包装到Map<String,dynamic>来解决Map.from问题。 Firestore文档数据值存储为Map<String,dynamic>,因为firestore允许所有 map (而不是 bool(boolean) 值)的任意值。由于您知道所有值都是 bool(boolean) 值(因为您在隐式Firestore模式中实现了约定),因此您需要使用Map<String,dynamic>将Firestore Map<String,bool>显式转换为Map.from:

import 'dart:convert';

void foo(Map<String,bool> boolMap) {}

void main() {
  // jsonDecode does not return Map<String,bool>, even though all items
  // in the serialized map are bools.
  // Maybe you obtained your map in a similar manner?
  final Map<String,dynamic> dynamicMap = jsonDecode('{"x":true}');
  
  // This line will fail because dynamicMap is not Map<String,bool>
  // foo(dynamicMap);

  // This line succeeds because Map.from will cast the dynamic
  // map to a Map<String,bool> since all types present in the
  // parent map have bool keys.
  // Otherwise, Map.from will fail.
  foo(Map.from(dynamicMap))
}
为了回答第二个问题,上面的代码应该可以正常工作,但是如果您设置了某些严格的类型检查选项,则可能需要显式转换条目的值:
void main() {
  final map = <String,dynamic>{};
  map.putIfAbsent('a', () => true);
  print(map);
  // Here is the explicit cast from dynamic to bool.
  // Obviously, you need to be sure that map['a'] is a bool or this will fail.
  final bool b = map['a'] as bool;
  print(b);
}

关于firebase - 如何为Map <String,dynamic>类型的映射添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62788179/

相关文章:

flutter - onGenerateRoute 被多次调用

dart - Flutter创建无限ListView.builder上下滚动

iOS Firebase 崩溃报告设置时崩溃

javascript - Firebase 事件保证子添加子删除

flutter - 导航后打开 flutter 对话框

flutter - 静态打字 hell

android - Flutter:显示大量图像而不出现OOM

dart - Flutter- 到目前为止,是否无法使用 Algolia 在 Firestore 中实现搜索功能?

javascript - 为什么我的 firebase 云函数进程从未完成?

firebase - Firebase 项目的公共(public)设置去了哪里?