【发布时间】:2020-03-07 14:18:41
【问题描述】:
在 Dart 中,我有一个像这样的类,它在 getter/setter 后面保护 _x,这使我可以控制对 _x 的更改:
//in a.dart
class A {
int _x;
int get x => _x;
set x(int value) {
bool validation_ok=true;
//do some validation/processing
if (validation_ok) {
_x = value;
//perform side effects that should happen every time _x changes e.g. save to SharedPreferences
print('Validated $value and side effects performed');
}
}
}
//in amain.dart
import 'a.dart';
void main() {
A a = A();
a.x = 5; //if validation successful stores 5 to _x and performs side effects
print(a.x); //prints 'Validated 5 and side effects performed' and then '5'
}
但是,如果我想保护 List 或对象而不是 int,我该怎么办?
//in b.dart
class B {
List<int> _y;
List<int> get y => _y;
set y(List<int> value) {
bool validation_ok=true;
//do some validation/processing
if (validation_ok) {
_y = value;
//perform side effects that should happen every time _y changes e.g. save to SharedPreferences
print('Validated $value and side effects performed');
}
}
}
//in bmain.dart
import 'b.dart';
void main() {
B b = B();
b.y = [5]; //if validation successful stores [5] to _y and performs side effects
print(b.y); //prints 'Validated [5] and side effects performed' and '[5]'
b.y.add(6); //now _y is [5,6] but no validation was done on 6 and no side effects performed
print(b.y); //prints '[5,6]' only
}
请注意,在 bmain.dart 中,b.y.add(6) 行会添加到私有列表中,而无需通过 setter。如何确保不允许此类访问并且对私有列表或对象的任何更改都受到控制?
【问题讨论】:
-
谢谢 - 该链接中的有用想法。
标签: dart