3

I need to dynamically create a List variable depending on the situation.

I have a List of strings. These were created dynamically.

List Categories = [name: 'String 1', name: 'String 2', name: 'String 3']

I need to create a List variable dynamically that can hold EACH string. Don't ask me why, but trust me.

I need something like this:

for(int i = 0 ; i < Categories.length ; i ++)
{
    // logic to create a variable of List type and even name it according to the value it is holding:
    List String1Var = Categories.[i].name

     // or even better : 

    List $Categories.[i].name = ....



 } 

so String1Var needs to be named as String1Var - i.e. the name itself has to be dynamic, and the contents too.

Is this possible in flutter?? Or have Google still yet to advance their language so it works for people like me?

Is that the right syntax? How do I dynamically create a variable name?

3

1 Answer 1

2

What you want can be done with the help of Map.

Instead of creating separate variables we are generating dynamic keys and storing the values in it, As Dart has no concept for dynamic variables.

Code:

  final Map myCategoryDynamic = {};

  for(int i = 0 ; i < Categories.length ; i ++)
  {
// logic to create a variable of List type and even name it according to the value it is holding:
    myCategoryDynamic['String'+i.toString()+'Var'] = Categories.[i].name;

  }

So when we need to check the values - we can check by - myCategoryDynamic[String1Var] myCategoryDynamic[String2Var] and so on...

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Anmol. Thanks for your excellent contribution. But I don't understand the line: myCategoryDynamic['String'+i.toString()+'Var']. If the element name is 'String1' - then the myCategoryDynamic should be called myCategoryDynamicString1
@Kiro777 - Thank You !! Instead of creating a separate variables we are generating dynamic keys -- and storing the values in it, As Dart has no concept for dynamic variables.
So when we need to check the values - we can check by - myCategoryDynamic[String1Var] myCategoryDynamic[String2Var] and so on...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.