【问题标题】:How to Add and Use key in Custom widget constructors如何在自定义小部件构造函数中添加和使用键
【发布时间】:2021-12-23 22:09:41
【问题描述】:

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

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});

解决警告通知?

【问题讨论】:

    标签: flutter dart constructor flutter-widget


    【解决方案1】:

    你可以使用:

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

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

    【讨论】:

      猜你喜欢
      • 2023-01-22
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 2013-08-28
      • 1970-01-01
      • 2011-05-17
      • 2012-03-07
      相关资源
      最近更新 更多