Home > Software engineering >  How to call a List with Strings to make the call dynamic
How to call a List with Strings to make the call dynamic

Time:07-22

I'm searching for create a dynamic form which contain DropDownButtons.

Before do that, I'm trying something on DartPad to know if it's possible to call a list with some Strings.

Below an example about what I want to do (maybe what I'm searching for is now possible) :

void main() {
  List<Map<String, String>> listOf3AInitial = [{"name": "4A"},
                                               {"name": "5A"}
                                              ];
  
  String _listOf = "listOf";
  String _year = "3A";
  String _type = "Initial";
  
  
  var listOfType = "$_listOf$_year$_type";
  
  
  print(listOfType);
}

In this case it print "listOf3AInitial" and I want to print the List {"name": "4A"},{"name": "5A"}.

How it is possible to do that ?

Regards

CodePudding user response:

You have to map a string of it's value to do so. For example

List<Map<String, String>> listOf3AInitial = [{"name": "4A"}, {"name": "5A"}];

Map<String, List<Map<String, String>>> list3AInitialMap = {
   "listOf3AInitial" : listOf3AInitial,
   }; 

Now you can get a value from this map like

String _listOf = "listOf";
  String _year = "3A";
  String _type = "Initial";
  
  
  var listOfType = "$_listOf$_year$_type";
  print(list3AInitialMap[listOfType]);

CodePudding user response:

Your var listOfType returns a String. Unfortunately, you cannot use/convert String as a variable name.

In this case, you may want to use a map:

  void main() {
  List<Map<String, String>> listOf3AInitial = [{"name": "4A"},{"name": "5A"}];
  List<Map<String, String>> listOf3BInitial = [{"name": "4B"},{"name": "5B"}];
  
  String _listOf = "listOf";
  String _yearA = "3A"; //A
  String _yearB = "3B"; //B
  String _type = "Initial";
  
  //Reference your lists in a map
  Map<String, dynamic> myLists = {
    "listOf3AInitial": listOf3AInitial,
    "listOf3BInitial": listOf3BInitial
  };
  
  //This returns your listOf3AInitial
  var listOfType = myLists["$_listOf$_yearA$_type"]; 
  print(listOfType);
  
  //You may also access it directly
  print(myLists["$_listOf$_yearB$_type"]);
}
  • Related