Search code examples
flutterlistdartfinal

How is it possible to add or remove method to final list?


I have fount out something. Assume, we have a final list and when I wanna use add or remove method, it allows to use. For example:

void main() {

  final exaList=[1,2,3,4];
  exaList.add(100);
  
  print(exaList);
}

I can't understand. I have added the final tag but that list still use add or remove methods. Please can anyone explain this situation?

Many Thanks..


Solution

  • See that's the difference between a final variable and a const variable. You cannot change the value of a final variable but you can modify it however you want which means that add or remove functions will work on the final variable, but if you want a completely immutable variable then what you need is const:

    void main() {
      
     const exaList=[1,2,3,4];
      exaList.add(100);
      
      print(exaList);
    }
    

    If you want, you can try to run this to understand how a final variable works :

    void main() {
      
      final exaList=[1,2,3,4];
      exaList = [2,3,4,5];
      
      print(exaList);
    }