Flutter Stateful widget - Part2 - How to Access State of Widget
Last updated Jan 04, 2020In the previous post explained what is Stateful widget and lifecycle of Stateful widget.
This post we are going to learn how to access state of the widget.
What is context ?
A context is a reference to the location of a Widget within the tree structure of all the Widgets which are built.
Each context is belongs to single widget
So state id linked to Context and context is linked to an instance of widget
Then how we will access State of widget?
- The Widget Itself
- Direct Child of Widget
- InheritedWidget
The Widget Itself : The Widget itself can only use the state
Direct Child of Widget
With the Key specification we can access the state.
class _MyWidgetState extends State { @override |
Here we maintained the state of widget by GlobalKey
InheritedWidget
The InheritedWidget is a special Widget, that we can put in the Widgets tree as a parent of another sub-tree
The InheritedWidget should be in top positioned at the top of widget tree to share the data accross.
Lets check the below code
class MyInheritedWidget extends InheritedWidget { @override |
Here widget name is MyInheritedWidget
As we know inheritedwidget should be on top, so we need to pass all widgets as child property.
@required Widget child
updateShouldNotify() will tell that whether need to modify the children if the data changed
In Next Post I will show examples on InheritedWidget
Article Contributed By :
|
|
|
|
5505 Views |