Search code examples
flutterdartstatic-variables

Static variables initialised using static variables are not updating


If I have an static variable (let's say foo) that has its value inherited from another static variable and later I change the value of that other static variable then try to access foo, it still gives the old value that it was initialised with.

I have a file endpoints.dart with following code

class EndPoints {

  static String baseUrl = "someurl.com/";

  static String place = baseUrl + "api/v1/place";

}

here if I change the baseUrl in any other file and print it like

onPressed () {
 
 print(EndPoints.place);
 //prints someurl.com/api/v1/place

 EndPoint.baseUrl = "changedurl.com/";

 print("${EndPoints.baseUrl}");
 //prints changedurl.com/

 print("${EndPoints.place}");
  //still prints someurl.com/api/v1/place
}

My concern is why static String place = baseUrl + "api/v1/place" not taking the updated baseUrl value.


Solution

  • Static member place will not be recalculated when changing baseUrl. You can define a custom getter function like this:

    class EndPoints {
      static String baseUrl = "someurl.com/";
      static String get place => baseUrl + "api/v1/place";
    }
    

    With this change your code will output the place with the updated value. Also, there is a typo in your code, EndPoint.baseUrl should be EndPoints.baseUrl.