Dynamically setting variable name in Dart

喜你入骨 提交于 2021-02-05 08:36:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/23039314/dynamically-setting-variable-name-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!