Keys In Flutter, widget in Flutter - Taleem Dunya

Lecture 11

Keys In Flutter, widget in Flutter

In Flutter, a Key is an object that identifies a widget. Every widget in Flutter has a unique identifier that is used by the framework to maintain the state of the widget tree. When a widget is updated, Flutter uses the Key to determine which widget needs to be updated. Keys are important when working with stateful widgets, such as when adding or removing items from a list. Without keys, the framework would not be able to tell which item in the list was updated or removed, and it would have to rebuild the entire list every time it changed.

There are two types of keys in Flutter:
GlobalKey:
A GlobalKey is a unique identifier that can be used to refer to a specific widget from anywhere in your app. Global keys are typically used when you need to access a widget outside of its parent widget, such as when using Navigator to push and pop screens.
ObjectKey:
An ObjectKey is a unique identifier that is based on the object identity of a widget. This means that two widgets with the same properties and parameters, but created at different times, will have different
ObjectKeys.
Object keys are typically used when working with stateful widgets, such as when adding or removing items from a list.
Here's an example of how to use keys in Flutter: