Search code examples
flutterdartvariablesstatic

Static and local variable connection in Flutter


I am confused and need some help about connection between static and local variable in flutter, please see my code attachment below,

void main() {
  var tempData = A.getData();
  var tmpMyInt = A.myInt;
  
  print("tmpMyInt Before: ${tmpMyInt.toString()}");
  print('tempData Before: ${tempData}');
  
  A.data[0]= "1 piggy";
  A.data[1]= "2 piggy";  
  A.myInt = 150;
  
  print('tempData after : ${tempData}');
  print("tmpMyInt after: ${tmpMyInt.toString()}");
}

class A {
  static List<dynamic> data = [
    "1","2"
  ];
  
  static int myInt = 10;

  static getData() {
    return data;
  }

  static setData(int idx, var value) {
    data[idx]= value;
  }
}

and for the debug output is:

tmpMyInt Before: 10
tempData Before: [1, 2]
tempData after : [1 piggy, 2 piggy]
tmpMyInt after: 10

I wonder why tempData value changed or is different between before and after and the same does not happen for tmpMyInt value?

As you can see in my code, I just change the static variable value (data and myInt) and never updated the new static variable value into tempData and tmpMyInt as a local variable in the main function.


Solution

  • First, I want to point out that this is a question about Dart programming language.

    • When you assign a complex object (like a List or Map) to a variable, you are actually assigning a reference to that object. This means that if you modify the object, the changes will be visible through any reference to that object.
    • For primitive types (like int, double, bool), when you assign a variable, you are making a copy of that value. So, changes to the original variable won’t affect the copied value.

    The difference in behavior between tempData and tmpMyInt is due to the fact that tempData is a reference to a mutable list object, while tmpMyInt is of type int.

    So A.data and tempData point to the same object and any modifications made via A.data are reflected when you print the value obtained from tempData. But in case of tmpMyInt and A.myInt, updates to A.myInt are not reflected in tmpMyInt.

    You can read the following resource for more in-depth explanation (this concept is similar across numerous programming languages):