Jay
Jay

Reputation: 37

Dynamically setting variable name in 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?

Upvotes: 3

Views: 2902

Answers (1)

lrn
lrn

Reputation: 71773

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.

Upvotes: 4

Related Questions