Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic variable NAME creation in Flutter

Tags:

flutter

dart

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?


1 Answers

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...

like image 192
anmol.majhail Avatar answered Apr 12 '26 13:04

anmol.majhail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!