0

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That solved the issue. Thanks :) also I changed the baseUrl to a getter to be on safe side.
1

You change the value of baseUrl, you don't touch the place. You can try to write a setter:

void setBaseUrl(String value) {
   this.baseUrl = value;
   this.place = baseUrl + "api/v1/place";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.