dart - How to return an immutable List in Dart?
问题描述
So in other languages there are ArrayList
or MutableList
which allows modifications (add, delete, remove) to list items. Now to avoid modification of these list, simply return the MutableList
or ArrayList
as a List
.
I want to do the same thing in Dart
. But in Dart
returning a List
still allows you to do list.add
. How can this be done properly in Dart?
解决方案
You may use Iterable<type>
. It is not a List<type>
, it does not provide methods to modify, but it does to iterate. It also provides a .toList()
method, if needed. Depending on your construction, it may be better to use Iterable
instead of List
to ensure consistency.
Almost good
final Iterable<int> foo = [1, 2, 3];
foo.add(4); // ERROR: The method 'add' isn't defined.
// Warning: following code can be used to mutate the container.
(foo as List<int>).add(4);
print(foo); // [1, 2, 3, 4]
Even though foo
is instantiated as a mutable List
, the interface only says it is a Iterable
.
Good
final Iterable<int> foo = List.unmodifiable([1, 2, 3]);
foo.add(4); // ERROR: The method 'add' isn't defined.
(foo as List<int>).add(4); // Uncaught Error: Unsupported operation: add
// The following code works but it is
// OK because it does not mutate foo as
// foo.toList() returns a separate instance.
foo.toList().add(4);
print(foo); // [1, 2, 3]
推荐阅读
- javascript - 自定义椭圆形 SVG 图像中的填充百分比区域
- php - Conditionally create URLwith php and pass to jquery.ajax
- java - Is the Sonar rule for Spring '"@RequestMapping" methods should be "public"' accurate?
- javascript - Invisible captcha does not work in Chrome Lite mode
- visual-studio - Is there a way to suppress error messages for specific C# types in Visual Studio 2019?
- java - form-data file upload + array of object
- antd - 如何从 antd modal 隐藏顶部的 X 按钮
- reactjs - 从数据库获取数据时的useEffect无限循环
- powershell - 如何在 ForEach-Object Parallel 中设置计数器 - PowerShell 7
- javascript - 重构分支以在包装组件之上呈现