FLUTTER如何根据传递的字符串名称获取变量? [英] FLUTTER How to get variable based on passed string name?

查看:681
本文介绍了FLUTTER如何根据传递的字符串名称获取变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将变量及其代码名称存储在类中。

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

假设我想从该课程中获取XVG,我想这样做

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?

推荐答案

在扑打中使用飞镖不支持反射

如果您要的是文本出于某种原因直接包含在您的代码中,建议您使用文本替换(使用您喜欢的工具或使用intellij的find +用正则表达式替换)将其更改为地图,即

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',
};

另一种方法是将其另存为 JSON 文件放在您的资产中,然后在应用程序打开时加载并读取它,或者在需要时甚至在首次运行时从服务器下载它(以防URL需要比您打算更新应用程序时更频繁地更新)。对这样的一堆数据进行硬编码不一定总是一个好主意。

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.

编辑:如何使用。

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

这篇关于FLUTTER如何根据传递的字符串名称获取变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆