Home > database >  Flutter - How to convert Map<String, String> from TextEditingController to a Map<String, dy
Flutter - How to convert Map<String, String> from TextEditingController to a Map<String, dy

Time:11-11

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?

CodePudding user response:

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

CodePudding user response:

You could use the map method to go through each element and cast it if necessary.

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);
  });
  • Related