Flutter - 如何将 Map<String, String> 从 TextEditorController 转换为 Map<String, dynamic> JSON



我有大约40个TextFormFields和我检索他们的值与TextEditingController。这些值被转换成Map<String,>通过以下步骤映射:

// map that stores controllers
Map<String, TextEditingController> storeControllers = controllers;
// convert to map that stores only controller texts
Map<String, String> currentSelections = storeControllers
.map((key, value) => MapEntry(key, storeControllers[key]!.text))

所有值都为String类型的当前输出:

//currentSelections map
Map<String, String>
{
"field1": "1",
"field2": "Two",
"field3": "0.03",
...
"field40": "four40",
}

我如何将currentSelections映射转换成一个JSON,将值存储在相应的类型中?

//Desired output:
Map<String, dynamic>
{
"field1": 1, //int
"field2": "Two", //String
"field3": 0.03, //double
...
"field40": "four40", //String
}

任何帮助将不胜感激!:)

我知道将字符串转换为其他类型的方法是使用int.parse("text")方法。但有这么多不同的类型,我该怎么做呢?

不妨试试这个

Map<String, dynamic> convert(Map<String, String> map) {
return {
for (final entry in map.entries)
entry.key: int.tryParse(entry.value) ??
double.tryParse(entry.value) ??
entry.value
};
}

的例子:

import 'dart:convert';
void main() {
Map<String, String> map = {
"field1": "1",
"field2": "Two",
"field3": "0.03",
"field40": "four40",
};
final newMap = convert(map);
print(jsonEncode(newMap));
//output: {"field1":1,"field2":"Two","field3":0.03,"field40":"four40"}
}

您可以使用map方法遍历每个元素并在必要时进行类型转换。

bool isInt(num value) => (value % 1) == 0;
final Map<String, dynamic> desireddMap = currentMap.map((key, value) {
dynamic newValue = value;
// Check if value is a number
final numVal = num.tryParse(value);
if (numVal != null) {
// If number is a int, cast it to int
if (isInt(numVal)) {
newValue = numVal.toInt();
} else {
// Else cast it to double
newValue = numVal.toDouble();
}
}
return MapEntry(key, newValue);
});

相关内容

最新更新