在Dart中修改类内的最终字段 [英] Modifying final fields inside the class in Dart

查看:110
本文介绍了在Dart中修改类内的最终字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dart文档读取:


如果您从未打算更改变量,请使用final或const,而不是
而不是var或除类型外。最终变量只能设置一次

If you never intend to change a variable, use final or const, either instead of var or in addition to a type. A final variable can be set only once;

好,这意味着第二次分配最终变量将不起作用,没有提及修改
的内容,即

Ok, this means that assigning a final variable second time will not work, but nothing is said about modifying, i.e.

void main() {
  final List<int> list = [1,2,3];  

  list = [10, 9, 8]; //error!

  list
  ..clear()
  ..addAll([10, 9, 8]); //works!
}

正如人们所看到的,我本质上是<- em>分配了最终变量 list

As one can see, in essence, I re- assigned final variable list. Doesn't it contradict the whole idea of final variables?

推荐答案

final 并不表示最终结局

即使修改列表内容,列表变量仍引用相同的列表实例。即使将任何可变实例分配给最终变量,也可以对其进行修改。
想象

The list variable references still the same list instance even when you modify the lists content. Any mutable instance can be modified even when it was assigned to a final variable. Imagine

void main() {
  var l = [1,2,3];
  final List<int> list = l;  
}

现在,您将无法修改引用的列表中的项目 l ,因为该列表也已分配给最终字段 list (均为 list l 引用相同的列表)。

Now you wouldn't be able to modify the items in the list referenced by l because the list is also assigned to the final field list (both list and l reference the same list). That doesn't make sense.

您可以使列表不可变的是

What you can do to make the list immutable is

final List<int> list = const[1,2,3];  

现在您不能将其他列表分配给列表,您将无法修改列表引用的列表的内容。

Now you can't assign another list to list and you can't modify the contents of the list referenced by list.

另一种方法

  import 'dart:collection'
  ...
  var l = [1,2,3];
  final List<int> list = UnmodifiablyListView(l);

现在您无法修改列表 list 引用的列表的内容,但是您可以修改 l list 会反映对 l 所做的更改。)

如果您删除对 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;

final 很不错,例如以确保列表字段永远不会设置为 null

final is nice when you for example want to ensure that the list field never is set to null.

class MyModel {
  final list = [];
}

列表字段是公开的,但没有人可以将 list 设置为例如 null

The list field is public but nobody can set list to for example null.

var model = new MyModel();
...
model.list.forEach(print);

永远不会失败,并出现 null没有方法' forEach'

这类似于

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

这篇关于在Dart中修改类内的最终字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆