【问题标题】:Flutter 2: Cast List<dynamic> into List<Map<String, String>>?Flutter 2:将 List<dynamic> 转换为 List<Map<String, String>>?
【发布时间】:2021-09-09 04:30:02
【问题描述】:

我正在尝试通过精确特定类型来正确编写颤振。

我正在从 Json 文件中收集数据并尝试将其转换为 List&lt;Map&lt;String, String&gt;&gt;

Future<void> _readJson() async {
    final String response = await rootBundle.loadString('lib/assets/vocabulary.json');
    final data = await json.decode(response);
    print(data);
    _words = List<Map<String, String>>.from(data);
  }

但是演员表不起作用。即使尝试了 Stackoverflow 上提出的多种解决方案,也没有一个能奏效。

_words 的类型为 List&lt;Map&lt;String, String&gt;&gt;

这是我实际得到的输出

I/flutter ( 3971): 0
I/flutter ( 3971): [{a: test1, b: test2}, {a: test3, b: test4}, {a: test5, b: test6}]
E/flutter ( 3971): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>'
E/flutter ( 3971): #0      new List.from (dart:core-patch/array_patch.dart:40:5)
E/flutter ( 3971): #1      _HomePageState._readJson (package:langage_trainer/pages/home/home_page.dart:108:14)
E/flutter ( 3971): <asynchronous suspension>
E/flutter ( 3971): 

有人可以帮忙将我的数据转换成我的 _words 类型吗?

【问题讨论】:

    标签: flutter dart casting dart-null-safety


    【解决方案1】:

    对于演员表,我使用从 json.decode 返回的对象中的说明符(作为 List,作为 Map

    Future<void> _readJson() async {
      final String response = await rootBundle.loadString('lib/assets/vocabulary.json');
      final List<Map<String, String>> data = (await json.decode(response) as List)
          .map((e) => e as Map<String, String>).toList();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 2021-03-27
      • 2021-05-20
      • 2020-09-04
      • 2021-02-28
      • 1970-01-01
      • 2020-04-01
      相关资源
      最近更新 更多