【问题标题】:Flutter - How to convert Map<String, String> from TextEditingController to a Map<String, dynamic> JSONFlutter - 如何将 Map<String, String> 从 TextEditingController 转换为 Map<String, dynamic> JSON
【发布时间】:2022-11-12 02:09:33
【问题描述】:

我有大约 40 个 TextFormField,我使用 TextEditingController 检索它们的值。这些值通过以下步骤转换为 Map<String, 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))

具有字符串类型的所有值的当前输出:

//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") 方法。但是涉及这么多不同类型的我该怎么做呢?

【问题讨论】:

    标签: json flutter dart flutter-web


    【解决方案1】:

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

    bool isInt(num value) => (value % 1) == 0;
    
    final Map<String, dynamic> desiredMap = 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);
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 2023-03-27
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多