avoid_ implementing_ value_ types
Learn about the avoid_implementing_value_types linter rule.
Don't implement classes that override ==.
Details
#
DON'T implement classes that override
==.
The == operator is contractually required to be
an equivalence relation; that is, symmetrically for all
objects o1 and o2,
o1 == o2 and o2 == o1
must either both be true, or both be false.
NOTE: Dart does not have true value types, so instead we consider a class that implements
==as a proxy for identifying value types.
When using implements, you do not inherit the
method body of ==, making it nearly impossible to
follow the contract of ==. Classes that override
==
typically are usable directly in tests
without creating mocks or fakes as well. For example,
for a given class Size:
class Size {
final int inBytes;
const Size(this.inBytes);
@override
bool operator ==(Object other) => other is Size && other.inBytes == inBytes;
@override
int get hashCode => inBytes.hashCode;
}
BAD:
class CustomSize implements Size {
final int inBytes;
const CustomSize(this.inBytes);
int get inKilobytes => inBytes ~/ 1000;
}
BAD:
import 'package:test/test.dart';
import 'size.dart';
class FakeSize implements Size {
int inBytes = 0;
}
void main() {
test('should not throw on a size >1Kb', () {
expect(() => someFunction(FakeSize()..inBytes = 1001), returnsNormally);
});
}
GOOD:
class ExtendedSize extends Size {
ExtendedSize(int inBytes) : super(inBytes);
int get inKilobytes => inBytes ~/ 1000;
}
GOOD:
import 'package:test/test.dart';
import 'size.dart';
void main() {
test('should not throw on a size >1Kb', () {
expect(() => someFunction(Size(1001)), returnsNormally);
});
}
Enable
#
To enable the
avoid_implementing_value_types rule, add
avoid_implementing_value_types
under
linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- avoid_implementing_value_types
If you're instead using the YAML map syntax to configure
linter rules, add
avoid_implementing_value_types: true under
linter > rules:
linter:
rules:
avoid_implementing_value_types: true
除非另有说明,文档之所提及适用于 Dart 3.12.2 版本报告页面问题.