Flutter Stateful widget - Part1 - Introduction - Lifecycle Methods

Introduction

Flutter we have two widgets 


Stateless widget
Widgets which never change its content dynamic called stateless widget

Stateful widget
Widgets which will change its behaviour/state dynamically called stateful widgets

 

Stateful widgets are useful when the part of the user
interface you are describing can change dynamically.
User interfaces need to respond to a variety of things:
The user doing something in the user interface.
Receiving data from another computer.
Time passing.


This is what Stateful Widgets are for. They store data
(state) in an associated State class and they can respond
when that data (state) changes as the result of the user
doing something

 

what is state?
A State defines the “behavioural” part of a StatefulWidget instance.

It holds information aimed at interacting / interferring with the Widget in terms of:

behaviour
layout


Sample Stateful widget code

class MyStatefulWidget extends StatefulWidget {
    MyStatefulWidget({
        Key key,
    }): super(key: key);
    
    
    @override
    _MyStatefulWidgetState createState() => new _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State {
    ...
    @override
    Widget build(BuildContext context){
        ...
    }
}

 

Two Classes

Each Stateful widgets combination of two classes
in the above code we can find it.

Class #1 

  • It extends Stateful Widget
  • This is the class is used to create a State Object 
  • This object could be create inside "createState" method.
  • The data inside this class is immutable
  • It is final and passed through the constructor same as for a Stateless widget.

 

Class #2 

  • It extends State 
  • This is the class wich will do the most of the work for the statefull widget
  • It holds the data that could be mutable
  • It builds the UI inside the build method
  • To change the UI based on data at run time we need to pass it inside setState() method

 

Execution flow while create Statefull widget

  • When you create a stateful widget 
  • The instance of class#1 is constructs
  • The Lifecycle method createState of class#1 will invokes to create instance of class#2
  • The Class#2 constructor willconstructs
  • The build method of class#2 will invoked to build the UI 

 

Know about Build Method

  • Stateful widgets build their UI in the build method
  • It can build their UI using values from their member variables, other sources
  • Build method force themselves to re-render
  • When stateful widgets calls setState() method it will rebuild the UI from the build method
     

LifeCycle methods

  • createState()
  • initState()
  • didChangeDependencies()
  • build()
  • didUpdateWidget()
  • setState()
  • deactivate()
  • dispose()

 

CreateState()
Flutter calls this method to create State Object

initState()
This method will called by flutter after constructor created.

didChangeDependencies()
Flutter calls this method when it detects that the data from te other sources has changed.
This will effects to re-render the build method.


didUpdateWidget()
Flutter calls this method when it has to throw away the
StatefulWidget (class #1) and replace it with another
StatefulWidget (class #1) of the same type but with
different data, which is then associated with State (class
#2). Now that the State is associated with a different
StatefulWidget.

build()
This method will executes while render the widget
The build(BuildContext context) method is called after the didChangeDependencies() (and didUpdateWidget)

setState()
This method calls by us to set state in the Widget


deactivet()
Rarely used. Flutter calls this method when State is
removed from the tree, but it might be reinserted before
the current frame change is finished. This method exists
basically because State objects can be moved from one
point in a tree to another


dispose()
Flutter calls this method when 'dispose()' is called when
the State object is destroyed

class MyStatefulWidget extends StatefulWidget {

    MyStatefulWidget({
        Key key,
        
    }): super(key: key);
    

    
    @override
    _MyStatefulWidgetState createState() => new _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State {

    @override
    void initState(){
        super.initState();
        
        // Additional initialization of the State
    }
    
    @override
    void didChangeDependencies(){
        super.didChangeDependencies();
        
        // Additional code
    }
    
    @override
    void dispose(){
        // Additional disposal code
        
        super.dispose();
    }
    
    @override
    Widget build(BuildContext context){
        return new ...
    }
}

 

Which widget should i use Stateless or Stateful widget?

This is the question every developer have do I need my Widget to be Stateless or Stateful?

"if the lifetime of widget, will you need to change any data dynamically"

if the answer is yes they you have to use Stateful widgetif no you can go with Stateless widget

 

Few exampls to use Stateful widget 

  • Form which shows the error messages on wrong fileds
  • UI which contains checkboxes to choose multiple options
  • Upload Images

 

Widget unique identity - Key
In flutter each widgets has unique identity by a key, which is defined by fraework at build time of widget.

This unique is optional while creating the widget
If we not pass key for widget, flutter will auto assign key for it.

If we needs to use key for any child widgets/ to access the widget we have to pass this key.

How we can hanlde the key of widget?
We have few helper class to hanlde the key of widgets

  • GlobalKey
  • LocalKey,
  • UniqueKey or ObjectKey

Global Key Example

GlobalKey newKey = new GlobalKey();
   
    @override
    Widget build(BuildContext context){
        return new NewWidget(
            key: newKey
        );
    }