1

I'm building a "Favorites" manager which has only 3 public features :

  • init(Iterable items) to initialize favorites (from preferences)
  • toggle(T item) to add/remove any favorite
  • contains(T item) to verify if an item is favorite

This works with a private List that is called _favorites.

I want to permit readonly access to this private list so that it can be displayed, but I want to prevent modifications like add() or remove() because it would break the Favorites class logical.

I think I can do this :

final List<T> _favorites;
List<T> get favorites => List.unmodifiable(this._favorites);

But although it does not allow add() or remove() at runtime... it does compile there is no linter warning.

Is it even possible to do what I want ?

Thanks.

Galactose
  • 175
  • 3
  • 8

1 Answers1

0

Per How to return an immutable List in Dart?, use Iterable instead of List for the property type.

final List<T> _favorites;
Iterable<T> get favorites => List.unmodifiable(this._favorites);
steve
  • 1,021
  • 1
  • 14
  • 29