简体   繁体   中英

How to Add and Use key in Custom widget constructors

I got notification warning (Not Error) about Use key in widget constructors. let say I have stateless class like this :

class TeaTile extends StatelessWidget {

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

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

the basic stateless format has a key like this :

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

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

I know how to disable the key rule use_key_in_widget_constructors: false . but I don't want to do it. so, how I add key in

final TheTea? tea;
  const TeaTile({this.tea});

to solve the warning notification?

You can just use:

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

Basically a combination of both, you're still taking a named parameter key , that will pass it's value to the super constructor, and another named parameter tea that would set your final variable value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM