【问题标题】:cannot assign value to my `Map<String, String>` variable after json-decodejson-decode 后无法为我的 `Map<String, String>` 变量赋值
【发布时间】:2019-01-14 22:00:46
【问题描述】:

我尝试在对我的Map&lt;String, String&gt; 变量进行 json 编码然后对其进行 json 解码之后为其分配一个值。以下代码示例是简化的重现;

import 'dart:convert';

String toJson(dynamic object) {
  var encoder = new JsonEncoder.withIndent("     ");
  return encoder.convert(object);
}

dynamic fromJson(String jsonString) {
  return json.decode(jsonString);
}

void main() {
  Map<String, String> data = {"hello": "world"};
  String jsonString = toJson(data);
  data = fromJson(jsonString);
  print(data);
}

当我运行它时,它失败了;

Unhandled exception:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>'

on this online editor 失败并出现不同的错误;

Uncaught exception:
TypeError: Instance of '_JsonMap': type '_JsonMap' is not a subtype of type 'Map<String, String>'

【问题讨论】:

    标签: json dart flutter


    【解决方案1】:

    解决方法,

    我不喜欢它,但它解决了这个问题。将fromJson函数返回的值包装成Map&lt;String, String&gt;.from(...)

    例如:

    void main() {
      Map<String, String> data = {"hello": "world"};
      String jsonString = toJson(data);
      data = Map<String, String>.from(fromJson(jsonString));
      print(data);
    }
    

    【讨论】:

    • 看起来类型不匹配。如果您将Map&lt;String, String&gt; data = {"hello": "world"}; 替换为Map&lt;String, dynamic&gt; data = {"hello": "world"};,它会起作用
    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多