无法在Flutter中将值从Map添加到列表

bmp9r5qi  于 2023-06-24  发布在  Flutter
关注(0)|答案(1)|浏览(198)

场景

我有一个来自API的序列化Json响应,如下所示:

"dropdownValues": "{\"Business Profits to Parents\":\"Business Profits to Parents\",\"Business Travel\":\"Business Travel\",\"Family Maintenance\":\"Family Maintenance\",\"Salary\":\"Salary\", \"Savings\":\"Savings\", \"Medical Expenses\":\"Medical Expenses\", \"Tuition Fees\":\"Tuition Fees\", \"Education Support\":\"Education Support\", \"Gift\":\"Gift\", \"Home Improvement\":\"Home Improvement\", \"Debt Settlement\":\"Debt Settlement\", \"Real Estate\":\"Real Estate\", \"Taxes\":\"Taxes\"}",

我将其解码为json,如下所示:

jsonDecode(dynamicFields["dynamicFields"][index]["dropdownValues"].replaceAll('\\', ''))

其中,dynamicFields["dynamicFields"][index]["dropdownValues"]是从API获取的序列化json。
上面的代码给了我一个Map<String,dynamic>,如下所示:

{
Business Profits to Parents: Business Profits to Parents, Business Travel: Business Travel, Family Maintenance: Family Maintenance, Salary: Salary, Savings: Savings, Medical Expenses: Medical Expenses, Tuition Fees: Tuition Fees, Education Support: Education Support, Gift: Gift, Home Improvement: Home Improvement, Debt Settlement: Debt Settlement, Real Estate: Real Estate, Taxes: Taxes
}

要求

我需要生成此Map的所有值的列表。为此,我使用以下代码:

jsonDecode(dynamicFields["dynamicFields"][index]["dropdownValues"].replaceAll('\\', ''))
                                                  .forEach((k, v) =>
                                                      dropDownLists[dropDownListsAdded]
                                                          .add(v))

问题

不幸的是,上面的代码无法执行,我无法生成List<String>
这里,dropDownListsList<List<String>>dropDownListsAdded是整数。

申请

我想知道为什么我的代码失败,以及如何修复这个问题,以便我能够填充字符串列表。

编辑

如果我使用a而不是dropDownLists[dropDownListsAdded],我会得到Null is not a sub type of String错误。
这里,aList<String>

au9on6nz

au9on6nz1#

API返回一个编码的JSON字符串。让我们把它赋给一个名为jsonString的变量:
final jsonString = dynamicFields["dynamicFields"][index]["dropdownValues"]
接下来,我们需要将JSON字符串解析为Map<String, dynamic>,这是Dart JSON格式:

import 'dart:convert';

final json = jsonDecode(jsonString);

jsonDecode函数负责解析任何特殊字符。您不需要手动从编码的JSON字符串中删除转义字符:<expr>.replaceAll('\\', ''))
因为jsonDecode函数负责所有解析工作。它接受一个输入JSON字符串,并将其转换为Map<String, dynamic>,现在您可以使用键访问数据:
final businessProfitsToParents = json["Business Profits to Parents"];
注意根据需要转换输出。例如,如果你的API返回一个数值(如double),那么你可以转换为:
... = json["Business Profits to Parents"] as double;
如果不确定数据类型,请使用类型提升以避免崩溃:

final json = jsonDecode(input["dropdownValues"] as String);
final value = json["Business Profits to Parents"];

if (value is double) {
  /// treat value as a double
}

相关问题