Search code examples
flutterdartencapsulation

Dart encapsulated list (just for observing values)


I have the following lists

List<ProductVariation> _productVariations = []; avoid null pointer exceptions
List<ProductVariation> get productVariations => _productVariations;

The main goal for adding List<ProductVariation> get productVariations => _productVariations; was to avoid _productVariations to be modified, however, I'm able to add, delete or do any operations inside the list, how can I prevent productVariations to be modified when accessed from another file?


Solution

  • An alternative solution is to use UnmodifiableListView from dart:collection which can be a lot more efficient since you are not making a new copy of the list but are instead just serving a protected view of your List:

    import 'dart:collection';
    
    class A {
      final List<int> _data = [1, 2, 3];
      UnmodifiableListView<int> get data => UnmodifiableListView(_data);
    }
    
    void main() {
      final a = A();
      print(a.data); // [1, 2, 3]
      a.data.add(5); // Unhandled exception: Unsupported operation: Cannot add to an unmodifiable list
    }
    

    A downside of this solution is that UnmodifiableListView is a normal List seen from the analyzers point of view so you will not get any statically errors from doing this. But you will get an exception on runtime if you try modify the list itself. For making it more clear for the developer I think it is nice to specify that the returned type is UnmodifiableListView even if you could just write List instead.

    Another point is that this solution (or the one suggested by Jigar Patel) does not prevents you from modifying the objects itself in the list if the objects are not immutable. So if you also want to prevent these changes you need to make deep copies of the objects.