Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

dart - FLUTTER How to get variable based on passed string name?

I have stored variables in a class with their code names.

Suppose I want to get XVG from that class, I want to do

String getIconsURL(String symbol) {

  var list = new URLsList();

  //symbol = 'XVG'

  return list.(symbol);
}

class URLsList{

var XVG = 'some url';
var BTC = 'some url';

}

Can someone help me achieve this or provide me with a better solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Dart when used in flutter doesn't support reflection.

If it's text that you want to have directly in your code for some reason, I'd advise using a text replace (using your favourite tool or using intellij's find + replace with regex) to change it into a map, i.e.

final Map<String, String> whee = {
  'XVG': 'url 1',
  'BTC': 'url 2',
};

Another alternative is saving it as a JSON file in your assets, and then loading it and reading it when the app opens, or even downloading it from a server on first run / when needed (in case the URLs need updating more often than you plan on updating the app). Hardcoding a bunch of data like that isn't necessarily always a good idea.

EDIT: how to use.

final Map<String, String> whee = .....

String getIconsURL(String symbol) {
  //symbol = 'XVG'

  return whee[symbol];
}

If you define it in a class make sure you set it to static as well so it doesn't make another each time the class is instantiated.

Also, if you want to iterate through them you have the option of using entries, keys, or values - see the Map Class documentation



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...