如何在自定义小部件构造函数中添加和使用键

How to Add and Use key in Custom widget constructors

我收到了关于 Use key in widget constructors. 的通知警告(不是错误)假设我有这样的无状态 class :

class TeaTile extends StatelessWidget {

  final TheTea? tea;
  const TeaTile({this.tea});  //the warning in hire!

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

基本的无状态格式有一个像这样的键:

class TeaTile extends StatelessWidget {
  const TeaTile({ Key? key }) : super(key: key);  //this one

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

我知道如何禁用密钥规则use_key_in_widget_constructors: false。但我不想这样做。所以,我如何在

中添加 key
final TheTea? tea;
  const TeaTile({this.tea});

解决警告通知?

您可以只使用:

final TheTea? tea;
const TeaTile({ Key? key, this.tea }) : super(key: key);

基本上是两者的结合,您仍然采用一个命名参数 key,它将把它的值传递给超级构造函数,另一个命名参数 tea 将设置您的最终变量值。