我知道,这个问题和DART find all the fields in class很相似。我想知道是否有什么方法可以在不使用镜像的情况下实现这一点?
我的用例如下:我使用 shared_preferences package存储许多值。对于键,我有一个这样的类:
class Key {
static const String FOO = 'foo';
static const String BAR = 'bar';
...
}
我想编写一个单元测试来检查此类常量不包含任何重复项。以下情况会导致错误:
class Key {
static const String FOO = 'foo';
static const String BAR = 'bar';
static const String ANOTHER = 'foo';
}
由于 dart:mirrors
在这里不起作用,实现测试的最佳方法是什么?
最佳答案
如果您的键恰好遵循命名变量的语法,则可以使用枚举
而不是类:
enum Key { foo, bar }
将类替换为枚举后,将对 Key.FOO
和 Key.BAR
的引用替换为 Key.foo.name
和 Key.bar.name
分别。作为奖励,使用枚举意味着您不必测试重复的键!
Dart 2.17(2022 年 5 月 11 日发布)引入了“增强枚举”。欢迎查看此article或Dart language tour了解您可以做什么的深入描述。
如果您希望能够使用任何字符串作为键,您可以创建一个增强的枚举:
enum Key {
foo('multiple words'),
bar('punctuation!');
final String keyname;
const Key(this.keyname);
@override
String toString() => keyname;
String call() => keyname;
}
bool noDuplicates() {
final List<String> keys = [for (final k in Key.values) k()];
return keys.length == keys.toSet().length;
}
toString()
和 call()
不是必需的,但当您想要将键表示为 "${Key 时,它们会很方便.foo}"
或 Key.foo()
而不必使用 Key.foo.keyname
。
关于flutter - 如何在不使用镜像的情况下获取 Dart 类的所有静态 const 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67353788/