编辑2(宏)
尽管宏还不是 Dart 规范的一部分(并且实际上是用于代码生成),但您实际上可以在此处使用它们进行类型检查(并且可以用于防止编译!)。在你的例子中,UseInt
将是一个类的第 3 阶段宏:
macro class UseInt implements ClassDefinitionsMacro {
const UseInt();
@override
Future<void> buildDefinitionForClass(
ClassDeclaration clazz, ClassDefinitionBuilder builder) async {
final fields = await builder.fieldsOf(class);
for (final field in fields) {
final type = await builder.resolve(field.type.code);
final isInt = false; // TODO probably could be done with something like type.isSubtypeOf but I haven't figured out the best way to do this yet
assert(isInt, '$field in $clazz is not of type int!');
}
}
}
您可以在此处阅读有关宏的更多信息:https://github.com/dart-lang/language/blob/master/working/macros/feature-specification.md https://github.com/dart-lang/language/blob/master/working/macros/feature-specification.md
编辑(插件)
我忘记了你实际上可以创建一个分析器/linter 插件。看这里:https://github.com/rrousselGit/riverpod/tree/master/packages/riverpod_lint https://github.com/rrousselGit/riverpod/tree/master/packages/riverpod_lint
和这里:
https://pub.dev/packages/custom_lint https://pub.dev/packages/custom_lint
原答案
这非常重要。
我稍微挖掘了几个不同包的源代码,看起来你也许可以制作一个 forklinter https://github.com/dart-lang/linter并定义您自己的自定义规则UseInt
。有很多例子;例如,您可以看到如何avoid_print
被定义为here https://github.com/dart-lang/linter/blob/main/lib/src/rules/avoid_print.dart.
但是,您提供的屏幕截图使用了must_be_immutable https://dart.dev/tools/diagnostic-messages#must_be_immutable,即实际上是在分析器本身中定义的 https://github.com/dart-lang/sdk/search?q=must_be_immutable。如果 linter 中的自定义规则无法实现您想要的目标,您可能需要分叉analyzer https://github.com/dart-lang/sdk/tree/main/pkg/analyzer并创建你自己的诊断信息 https://dart.dev/tools/diagnostic-messages在分析仪的叉子中。