Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically setting variable name in Dart

Tags:

dart

I had saved a variables name and value to a JSON file in Dart. Later I extracted the name and value from that JSON file and now am trying to create a new variable with that name. Something like this:

var variableName= "firstName";
String variableName = "Joe";

so that:

String firstName = "Joe";

Is there a way to do this?

like image 988
Jay Avatar asked Feb 06 '26 14:02

Jay


1 Answers

Short answer: No.

You cannot create variables at runtime in Dart. The compiler assumes that all variables are visible when the program (or any single method) is compiled.

The way variables are looked up in Dart is that "x" refers to a local, static or top-level variable, if there is such a variable in the lexical scope, and it refers to "this.x" if there is variable in the lexical scope named "x".

If you could add a variable later, you would be able to change "x" from meaning "this.x" to meaning something else. Already compiled code would then be incorrect.

like image 125
lrn Avatar answered Feb 12 '26 12:02

lrn