如何强制 Flutter/Dart 要求类型?

How do I force Flutter/Dart to require types?

我习惯于依靠编译器来捕捉不兼容的类型错误。默认情况下,Dart 仅在我记得指定类型时才提供此功能。如果我忘记在代码中包含类型,那么我就不会进行类型检查。

如何让 Flutter/Dart 编译器在以下代码的指示行上出错?尽管充满了类型错误,但这段代码编译得很好。

class Foo {
  String foo() {
    return "foo";
  }
}

class Bar {
  String bar() {
    return "bar";
  }
}

f() { // would like a missing return type error here (e.g. void)
  print("returns nothing");
}

void g(x) { // would like a missing parameter type error here...
  print(x.bar); // ...so this isn't a missing property at runtime
}

void h() {
  String a = f(); // would like this to error...
  print("$a");  // ...instead of this printing "null"
  g(Foo()); // would like this to error for incorrect parameter type
}

如果有办法做到这一点,我该如何在 Visual Studio Code 和 Intellij/Android Studio 以及 dart2js 中做到这一点?

您可以使用 analysis_options.yaml 文件使 Dart 更严格。

analyzer:
  strong-mode:
    implicit-casts: false
    implicit-dynamic: false

将此文件放在项目的根目录中。

这将禁用 Dart 使用 dynamic 回退并使其成为编译错误的情况。

它还禁用隐式向上转换,如下所示:

Object a = 42;
String b = a; // unless `implicit-cast` is disabled, this is valid

另一种方法是调用 Dart Analyzer:

https://dart.dev/tools/dartanalyzer

示例文件:

main() {
   print('May');
}

结果:

PS C:\> dartanalyzer.bat --no-implicit-dynamic a.dart
Analyzing a.dart...
  error - Missing return type for 'main'. - a.dart:1:1 - implicit_dynamic_return