Home > Mobile >  How to Add and Use key in Custom widget constructors
How to Add and Use key in Custom widget constructors

Time:11-12

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?

CodePudding user response:

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.

  • Related