splaytreez
splaytreez

Reputation: 834

How to create a "constant reference" getter in Dart?

Say I have a class ListContainer that contains and manages a list that must be accessible from outside. Since managing this list is complicated, I don't want to let anyone other than ListContainer modify it. In C++, I would create a function that returns const reference, but in Dart, const works completely differently. Just using getter will not prevent someone from modifying the list.

So how can I provide an access to the list values without allowing to modify the list?

I'm looking for something better than creating a getNth function because that would also require creating methods like length, map, and so on.

Upvotes: 2

Views: 748

Answers (1)

Adnan Alshami
Adnan Alshami

Reputation: 1059

I think UnmodifiableListView is what you are looking for.

check out UnmodifiableListView Documentation

you can use it like this:

List<int> _myList = [1, 2, 3];
UnmodifiableListView<int> get myList => UnmodifiableListView(_myList);

Upvotes: 3

Related Questions