Galactose
Galactose

Reputation: 247

How to forbid List add() method in Dart?

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

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.

Upvotes: 1

Views: 269

Answers (1)

steve
steve

Reputation: 1179

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);

Upvotes: 0

Related Questions