What is a purpose to provide a key when creating public widgets?

In flutter_lints the use_key_in_widget_constructors lint requres providing a key when creating public widgets.

It's a good practice to expose the ability to provide a key when creating public widgets.

class MyPublicWidget extends StatelessWidget {
  MyPublicWidget({Key? key}) : super(key: key);
}

What is actualy the purpose of this lint rule i.e. what it gives?


Solution 1:

This is a convention. All widgets should allow specifying a key.
Your app won't suddenly stop working if a widget doesn't, but respecting that convention is a good thing.

It'd be inconvenient for users of a widget if they need to specify a key but that widget doesn't allow them to.

Solution 2:

As this article states:

  1. Multiple widgets of the same type and at the same level in a widget tree may not update as expected unless they have unique keys, given that these widgets hold some state.
  2. Explicitly setting a key to a widget helps Flutter understand which widget it needs to update when state changes.
  3. Among other things, keys also store and restore the current scroll position in a list of widgets.