final
不等于deep final
.
即使在修改列表内容时,list
变量仍引用相同的列表实例.任何可变实例都可以修改,即使它被赋给了最终变量.
想象一下
void main() {
var l = [1,2,3];
final List<int> list = l;
}
现在,您将无法修改由l
引用的列表中的项,因为该列表还被分配给最终字段list
(list
和l
都引用同一列表).那也太没道理了.
要使列表不可变,您可以做的是
final List<int> list = const[1,2,3];
现在,您不能将另一个列表分配给list
,也不能修改list
引用的列表的内容.
另一种方式
import 'dart:collection'
...
var l = [1,2,3];
final List<int> list = UnmodifiablyListView(l);
Now you can't modify list
or the contents of the list referenced by list
but you can modify the contents referenced by l
(list
would reflect the changes made to l
).
If you loose the reference to l
you have no way of modifying the contents.
var l = [1,2,3];
final List<int> list = UnmodifiablyListView(l);
l = null;
例如,当您想要确保list
字段永远不会设置为null
时,final
很好.
class MyModel {
final list = [];
}
list
字段是公共的,但是没有人可以将list
设置为例如null
.
var model = new MyModel();
...
model.list.forEach(print);
will never fail with an exception like null doesn't have a method 'forEach'
.
This is similar but more concise than
class MyModel {
var _list = [];
List get list => _list;
}