【问题标题】:How to add a value to a map of type Map<String, dynamic>?如何向 Map<String, dynamic> 类型的地图添加值?
【发布时间】:2020-10-28 11:22:01
【问题描述】:

这张地图会记录谁点赞了帖子,谁没有点赞。该字符串存储用户 ID,该值是他是否支持该帖子的布尔值。我最初使用 Map 但出现错误,提示“InternalLinkedHashMap 不是 Map 的子类型。因此,我将值从 bool 类型更改为动态。但是,以下代码似乎不适用于动态类型。如何更改代码并将布尔值初始化为动态类型的 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'];
}

【问题讨论】:

  • 请发布更多代码。特别是在地图初始化的地方。这通常与在初始化时没有指定正确的类型有关。
  • @SebastianK 嗨,我已经包含了 initState 和 Experience 类的代码。

标签: firebase flutter dart


【解决方案1】:

首先,您可以通过用Map.from 包装您的Map&lt;String,dynamic&gt; 值来解决您的Map&lt;String, bool&gt; 问题。 firestore 文档数据值存储为Map&lt;String,dynamic&gt;,因为 firestore 允许所有地图的任意值,而不仅仅是布尔值。由于您知道所有值都是布尔值(因为您在隐式 Firestore 架构中强制执行约定),因此您需要使用 Map.from 将 Firestore Map&lt;String,dynamic&gt; 显式转换为 Map&lt;String,bool&gt;

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);
}

【讨论】:

    【解决方案2】:

    您放置的是函数而不是布尔值,这就是发生错误的原因,只需使用 (true/false)

    widget.experience.upvotes.putIfAbsent(uid, false);

    希望这会有所帮助:)

    【讨论】:

    • 我不能这样做,因为有一个错误说'参数类型布尔不能分配给参数类型动态函数()'
    猜你喜欢
    • 2021-11-15
    • 2019-09-21
    • 2018-12-14
    • 2021-10-08
    • 1970-01-01
    • 2019-04-03
    • 2021-04-11
    • 1970-01-01
    • 2019-05-02
    相关资源
    最近更新 更多