首页 > 解决方案 > 如何在类构造函数中初始化最终属性

问题描述

我想通过其他字段初始化一个字段,例如服务器 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/";
  }
}

标签: flutterdart

解决方案


首先,您所拥有的应该可以正常工作(前提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呢?注意:您也可以像上面显示的那样传递给构造函数。isDevisProdisQaenv

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/";
  }
}

推荐阅读