Search code examples
flutterdartconstructorflutter-widget

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?


Solution

  • Update for Dart 2.17 using Super Initializers:

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

    The super keyword in a constructor is a shortcut for the method below.

    Older Dart versions:

    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.