mr_robot
mr_robot

Reputation: 547

How to initialize final properties in class constructor

I want to initialize a field by other field for example server URL and image URL should be also final

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

Upvotes: 1

Views: 341

Answers (3)

O Thạnh Ldt
O Thạnh Ldt

Reputation: 1223

You can set the default value inside Contructor of your class.

   class YourClass {
          YourClass ({bool a=true, String b= "example",});
          final bool a;
          final String b;
    
        }
  • Later, you can call: var instance = YourClass(); it means instance have default value: a=true and b='example'.
  • If you want change value: var otherInstance = YourClass(a:false,b:"newValue");

Upvotes: 0

Caleb Robinson
Caleb Robinson

Reputation: 1120

First of all, what you have should work just fine (provided that EnvironmentConfig.app_env is accessing a static variable). However, if you want to do the more traditional way of make final variables, take this route:

class Config {
  final bool isDev;
  final bool isProd;
  final bool isQA;
  
  // Other variables
  Config(this.isDev, this.isProd, this.isQA) {
    // Other code
  }
}

But why not have a final env variable and use getters for isDev, isProd, and isQa? Note: you could also pass in env to the constructor as I showed above.

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

Upvotes: 2

Tasnuva Tavasum oshin
Tasnuva Tavasum oshin

Reputation: 4750

Example:

 class _A {
      _A(bool limitPages, int pagesToDisplay)
      final int pagesToDisplay;
      final bool limitPages;
    }

Upvotes: 1

Related Questions