gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 07:08:55 27 4
gpt4 key购买 nike

我习惯于依靠编译器来捕捉不兼容的类型错误。默认情况下,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

关于flutter - 如何强制 Flutter/Dart 要求类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57629140/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com