'flutter how can i cast String to TextEditingController

hi i'm looking for a way to cast String variable into TextEditingController

  final TextEditingController _testController=TextEditingController();

and this is what i'm doing

var test = "_"+"testController"

and inside TextFormField Controller i'm calling controller like this

TextFormField(
controller: test,
),

I know i could've just called it by the name of TextEditingController _testController but i have to do it this way, any ideas how ? i tried casting the variable to TextEditingController but i get this error saying that

type 'String' is not a subtype of type 'TextEditingController' in type cast


Solution 1:[1]

As you mentioned in the comments you have 28 TextEditingControllers.

You could get access to the right one by creating a Map.

var test = "_"+"testController"
final TextEditingController _testController=TextEditingController();
final TextEditingController _nameController=TextEditingController(); //Second controller

Map<String, TextEditingController> textMap = {'_testController': _testController, '_nameController': _nameController}; //Map declaration

and then use it as:

    TextFormField(
     controller: textMap[test], //Access to the right controller by String Key
     ),

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dani3le_