【问题标题】:Flutter, Dart, add nested map to mapFlutter、Dart、给地图添加嵌套地图
【发布时间】:2022-12-12 08:59:57
【问题描述】:
var a = {
   'field1' : 'one'
   'field2' : 'two'
}

然后我想添加地图 b。

所以我试过了

a['b'] = {
  'nestedKey':{
     'field1' : 'one'
   }
};

但它发生错误。我如何实现这一目标?

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String?' of 'value'

eamirho3ein 的回答有效,但这仍然无效 我添加更多这不起作用

                      Navigator.of(context).pushAndRemoveUntil(
                          MaterialPageRoute(
                              builder: (context) => ScreenB(
                                    args: {
                                      'oldfield': 'old' 
                                    },
                                  )),
                          (Route<dynamic> route) => false);




import 'package:flutter/material.dart';

class ScreenB extends StatelessWidget {
  final args;
  const ScreenB({Key? key, required this.args}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    args['newfield'] ={
      'nested':{
        'field1' : 'one'
      }
    };
    print($args);
    return Container();
  }
}

【问题讨论】:

  • 你会包括你的结果和错误信息吗?
  • @eamirho3ein 我补充道

标签: flutter dart


【解决方案1】:

您需要像这样将 a 定义为 Map&lt;String, dynamic&gt;

Map<String, dynamic> a = {'field1': 'one', 'field2': 'two'};
a['b'] = {
   'nestedKey': {'field1': 'one'}
};

print("result = $a"); // result = {field1: one, field2: two, b: {nestedKey: {field1: one}}}

当你将a定义为var时,默认情况下它的类型采用Map&lt;String, String&gt;,当你尝试传递b时,因为b的值是另一个map所以你不能设置它,@987654329 @ 只接受字符串作为它的值。所以你需要把a的类型改成Map&lt;String, dynamic&gt;

【讨论】:

  • 您好,您的回答有效,但在我的环境中,它无效。请检查我编辑的问题
猜你喜欢
  • 2021-07-26
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 2021-09-30
  • 2021-07-03
  • 1970-01-01
相关资源
最近更新 更多