Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FLUTTER How to get variable based on passed string name?

Tags:

flutter

dart

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?

like image 691
Musa Usman Avatar asked Apr 17 '18 06:04

Musa Usman


1 Answers

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


like image 131
rmtmckenzie Avatar answered Sep 23 '22 01:09

rmtmckenzie