flutterapidartglobal-variablesglobalization

Global variable is not getting updated in dart Why?


I have two global variables. the first variable is assigned inside the second variable.When I update the first variable the second one is not getting updated.

    String value = "abcd";
    String value1 = "$value efgh";
    
    void main() {
      print(value);
      print(value1);
      value = "Zxy";
      print(value);
      print(value1);
    }

Result:

abcd
abcd efgh
Zxy
abcd efgh

To my understanding when I reassigned the first variable with different value.But the second variable don't know about this.That why it is printing the previous value. Its something similar to final.you can only change the value once after initialization.

If my understanding of this function is wrong please explain what is exactly happening and also tell me if there is anyway to change the global variable without the setState or statemanagement.


Solution

  • value1 = "$value efgh";
    

    The value of the variable value is directly positioned within the literal where you specified the $value. This is called String Interpolation in Dart.

    This does not mean that whenever value changes, value1 will change. value1 was already initialized as "abcd efgh". So changing value has no effect.


    What you can instead do is create a function that returns value1. Each time you call it, it constructs the string using value and returns it.

    String value = "abcd";
    String value1() {
        return "$value efgh";
    }
    
    print(value1()); // abcd efgh
    value = "xyz";
    print(value1()); // xyz efgh
    

    Dart has a feature where you can create Getters [See Getters and Setters in Dart] which are like methods but they can be referenced without calling them with parenthesis (). This behaves more like a variable than a function.

    String value = "abcd";
    String get value1 {
        return "$value efgh";
    }
    
    print(value1); // abcd efgh
    value = "xyz";
    print(value1); // xyz efgh
    

    Note that you can not assign the value1 when you use a function or getter.