flutter 中 required 和 @required 的区别是什么?它们之间有什么区别,我们什么时候需要使用它们?

what is the difference between required and @required in flutter. What is the difference between them and when do we need to use them?

如果我从命名参数中删除 required,它会给我一个错误:

The parameter 'color' // can't have a value of 'null' because of its type, but the implicit default value is 'null'.

它们有什么区别,我们什么时候需要使用它们?

class RoundedButton extends StatelessWidget {
  late final Color color;
  final String title;
  final VoidCallback? onPressedInput;

  RoundedButton(
      {required this.color,
      required this.title,
      @required this.onPressedInput});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 16.0),
      child: Material(
        color: color,
        borderRadius: BorderRadius.circular(30.0),
        elevation: 5.0,
        child: MaterialButton(
          onPressed: onPressedInput,
          minWidth: 200.0,
          height: 42.0,
          child: Text(
            title,
          ),
        ),
      ),
    );
  }
}

@required 只是一个注释,它允许分析器让您知道您缺少一个命名参数,仅此而已。因此您仍然可以编译应用程序,如果未传递此命名参数,则可能会出现异常。

然而,dart 中添加了可靠的 null-safety,并且 required 现在是一个需要传递给命名参数的关键字,这样它就不会让编译器 运行 如果这样参数未传递。它使您的代码更加严格和安全。

如果您真的认为这个变量可以为空,那么您可以通过在它后面添加一个 ? 来更改类型,这样就不需要 required 关键字,或者您可以为参数添加一个默认值。

https://dart.dev/null-safety/faq#how-does-required-compare-to-the-new-required-keyword

The @required annotation marks named arguments that must be passed; if not, the analyzer reports a hint.

With null safety, a named argument with a non-nullable type must either have a default or be marked with the new required keyword. Otherwise, it wouldn’t make sense for it to be non-nullable, because it would default to null when not passed.

When null safe code is called from legacy code the required keyword is treated exactly like the @required annotation: failure to supply the argument will cause an analyzer hint.

When null safe code is called from null safe code, failing to supply a required argument is an error.

What does this mean for migration? Be careful if adding required where there was no @required before. Any callers not passing the newly-required argument will no longer compile. Instead, you could add a default or make the argument type nullable.