flutter - 如何在类构造函数中初始化最终属性
问题描述
我想通过其他字段初始化一个字段,例如服务器 URL 和图像 URL 也应该是最终的
class Config {
final bool isDev = EnvironmentConfig.app_env == "development";
final bool isProd = EnvironmentConfig.app_env == "production";
final bool isQA = EnvironmentConfig.app_env == "qa";
String localHost = Platform.isAndroid ? "10.0.2.2" : "localHost";
String serverUrl;
String imageUrl;
Config() {
if (this.isDev) {
this.serverUrl = "http://$localHost:3000";
} else if (this.isProd) {
this.serverUrl = "";
} else if (this.isQA) {
this.serverUrl = "";
} else {
print("error: " + EnvironmentConfig.app_env);
}
this.imageUrl = this.serverUrl + "/api/files/image/";
}
}
解决方案
首先,您所拥有的应该可以正常工作(前提EnvironmentConfig.app_env
是访问静态变量)。但是,如果您想做更传统的制作最终变量的方法,请采用以下路线:
class Config {
final bool isDev;
final bool isProd;
final bool isQA;
// Other variables
Config(this.isDev, this.isProd, this.isQA) {
// Other code
}
}
但是为什么不使用最终变量并为、和env
使用 getter呢?注意:您也可以像上面显示的那样传递给构造函数。isDev
isProd
isQa
env
class Config {
final String env = EnvironmentConfig.app_env;
bool get isDev => env == "development";
bool get isProd => env == "production";
bool get isQA => env == "qa";
String localHost = Platform.isAndroid ? "10.0.2.2" : "localHost";
String serverUrl;
String imageUrl;
Config() {
if (this.isDev) {
this.serverUrl = "http://$localHost:3000";
} else if (this.isProd) {
this.serverUrl = "";
} else if (this.isQA) {
this.serverUrl = "";
} else {
print("error: " + env);
}
this.imageUrl = this.serverUrl + "/api/files/image/";
}
}
推荐阅读
- python - 使用 PyGame 中的操纵杆模块
- mysql - SQL Join 2 个表,即使没有匹配的数据
- firebase - Firestore:获取带有和不带有子集合数据的集合
- python - 在python的另一个文件中写入文件行
- javascript - ES6 子类继承属性
- assembly - 用于加载 bin 的简单引导加载程序
- php - 如何在php中找到一个至少有3个大于4的值的数组
- c++ - 使用柯南和 Cmake 对 Boost 存档的未定义引用
- c# - ASP.NET Core 2.0 Identity 将主键从字符串修改为 Guid
- reactjs - 可以在 componentDidUpdate() 上调度更新商店的操作吗?