Search code examples
flutterdartglobal-variables

Flutter Global Variable value gets set when list is filtered


was not sure how to phrase this question but am struggeling with the following at the moment. I have a global variable as such:

class GlobalVariables{ 
  static List<Activity> globalActivities = [];
}

I fill the list initially in my homescreen class. This works. I have a second screen where I use the variable to initialize my list of items. Here a user can filter this activity list and based on the filter I remove items dynamically from the local list. Somehow my global variable mimics now the number of entries of this local list which I do not understand. Maybe its too early but not sure whats going on.

@override
Widget build(BuildContext context) {

activities = globals.GlobalVariables.globalActivities;
print("act list start: ${globals.GlobalVariables.globalActivities.length}");
// final activities = Provider.of<List<Activity>>(context) ?? [];

// MyUser user = Provider.of<MyUser>(context);


if(widget.typefilter == "Tunnel"){
  print("act list mid 0: ${globals.GlobalVariables.globalActivities.length}");
  activities.removeWhere((i){
    if (i.type == 'Other'){
      return true;
    }else{
      return false;
    }
  });
  print("act list mid 0b: ${globals.GlobalVariables.globalActivities.length}");
}else if (widget.typefilter == "Other"){
  activities.removeWhere((i){
    if (i.type == 'Tunnel'){
      return true;
    }else{
      return false;
    }
  });
}else{
  //nothing
}
print("act list mid 1: ${globals.GlobalVariables.globalActivities.length}");

The printlog logs like this:

flutter: act list start: 1978
flutter: act list mid 0: 1978
flutter: act list mid 0b: 0
flutter: act list mid 1: 0
flutter: act list end 0: 0

It is correct that the activities list should be 0 but why is my global list now 0 as well?

thanks, timo


Solution

  • When you initialize activities with activities = globals.GlobalVariables.globalActivities;, you aren't creating a new List but are creating an extra reference to the existing List< Activity>.

    If you don't want changes to activities to reflect on globalActivities, you'll need to make a copy, for example with List.of():

    List<Activity> activities = List.of(globals.GlobalVariables.globalActivities);
    

    Note that this will be a shallow clone. You won't have a deep copy of the Activity inside, but it will again be a reference. This means that if you were to change something in the Activity object from one list, the same Activity object in the other list will have the same changes. This seems fine for your use case.