Flutter Stateful widget - Part2 - How to Access State of Widget

Last updated Jan 04, 2020

In 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 {
        /// the unique identity of the Scaffold
        final GlobalKey _scaffoldKey = new GlobalKey();

        @override
        Widget build(BuildContext context){
            return new Scaffold(
                key: _scaffoldKey,
                appBar: new AppBar(
                    title: new Text('My Widget'),
                ),
                body: new Center(
                    new RaiseButton(
                        child: new Text('Check Me'),
                        onPressed: (){
                            _scaffoldKey.currentState.showSnackBar(
                                new SnackBar(
                                    content: new Text('Showing sncakbar with State access'),
                                )
                            );
                        }
                    ),
                ),
            );
        }
    }
    

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 {
   MyInheritedWidget({
      Key key,
      @required Widget child,
      this.data,
   }): super(key: key, child: child);
    
   final data;
    
   static MyInheritedWidget of(BuildContext context) {
      return context.inheritFromWidgetOfExactType(MyInheritedWidget);
   }

   @override
   bool updateShouldNotify(MyInheritedWidget oldWidget) => data != oldWidget.data;
}

 

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 :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

5191 Views