Home > Software engineering >  flutter how can i cast String to TextEditingController
flutter how can i cast String to TextEditingController

Time:02-11

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

CodePudding user response:

You can't do it like that.

Maybe you can do something like:

TextEditingController controllers (String key) {
    switch(key) {
      case '_testController': return _testController;
    }
}

and in your TextFormField you can do

TextFormField(
controller: controllers(test),
),

CodePudding user response:

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
     ),
  • Related