Search code examples
jsonflutterdartflutter-web

Flutter - How to convert Map<String, String> from TextEditingController to a Map<String, dynamic> JSON


I have about 40 TextFormFields and I retrieve their values with TextEditingController. The values are converted into a Map<String, String> map via the following step:

// 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))

The current output with all values in String type:

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

How do I convert the currentSelections map into a JSON that stores the values in their corresponding types?

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

Any help would be appreciated! :)

I understand that the way to convert Strings to other types is using int.parse("text") method. But how do I do it with so many different types involved?


Solution

  • Maybe try with this

    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
      };
    }
    

    Example:

    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"}
    }