I'm used to relying on the compiler to catch incompatible type mistakes. By default, Dart offers this only if I remember to specify types. If I forget to include types in the code, then I don't get the type checks.
How do I get the Flutter/Dart compilers to error on the indicated lines in the following code? This code compiles just fine despite being full of type errors.
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
}
If there is a way to do this, how do I do it in Visual Studio Code and Intellij/Android Studio, as well as in dart2js?
You can use the analysis_options.yaml
file to make Dart stricter.
analyzer:
strong-mode:
implicit-casts: false
implicit-dynamic: false
Put this file in the root of your project.
This will disable the situations where Dart fallback with dynamic
and make it a compile error.
It also disable implicit upcasts like followed:
Object a = 42;
String b = a; // unless `implicit-cast` is disabled, this is valid