Get Variables name by it's value in Dart Lang

那年仲夏 提交于 2021-02-08 23:43:09

问题


For Example, I have a variable like this.

var fooBar = 12;

I want a something like this in Dart lang.

print_var_name(fooBar);

which prints:

fooBar

How can I achieve that? Is this even possible?

Thank you.


回答1:


There is no such thing in Dart for the web or for Flutter.
Reflection can do that, but reflection is only supported in the server VM because it hurts tree-shaking.

You need to write code for that manually or use code generation where you need that.

An example

class SomeClass {
  String foo = 'abc';
  int bar = 12;

  dynamic operator [](String name) {
    switch(name) {
      case 'foo': return foo;
      case 'bar': return bar;
      default: throw 'no such property: "$name";
    }
  }
}

main() {
  var some = SomeClass();
  print(some['foo']);
  print(some['bar']); 
}


来源:https://stackoverflow.com/questions/53737110/get-variables-name-by-its-value-in-dart-lang

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