MOBILE APPLICATION
DEVELOPMENT WITH FLUTTER
LESSON 3: STATEFUL WIDGETS
OUTLINE
What you will learn
• Widget tree
• Build method and BuildContext
• Stateful widget
• Life cycle methods
• ListView widget
• GridView widget
• Form and inputs
Widget Tree
• The widget tree is the logical representation of
all the UIs widgets. It is computed during layout
and used during rendering (frame to screen).
• Consider the following diagrams showing
widgets and corresponding widget tree.
3 icons with a label
Visual layout
Build Method
Recall how we Create a stateless widget:
class HelloWorld extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(…)
}
}
• The build method returns a Widget object that gives Flutter configuration
information about the widget (and any child widgets that it may be composed of).
• The first argument to the ‘build’ method of your Widget is the BuildContext. This
gives your ‘build’ method information about the location of your Widget in the
Widget Tree.
Build Context
• The addition of widgets makes the tree bigger and places new items on
the screen. The context parameter in build(BuildContext context)
gives important information about the position of the leaf in the tree.
In particular:
• A BuildContext instance is used by Flutter to know details about the
widget when the tree is being traversed;
• Each widget has its own BuildContext instance which becomes the
parent context of the widget(s) returned by its build method.
Stateful Widgets
So far we have been creating widgets that are stateless i.e does not
change when user interacts with them.
• A stateless widget never changes. Icon, IconButton, and Text are
examples of stateless widgets. Stateless widgets subclass
StatelessWidget.
• A stateful widget is dynamic: for example, it can change its
appearance in response to events triggered by user interactions or
when it receives data. Checkbox, Radio, Slider, InkWell, Form, and
TextField are examples of stateful widgets. Stateful widgets subclass
StatefulWidget.
Stateful widgets cont…
• A stateful widget has internal state and can
manage that state. All stateful widgets
have corresponding state objects i.e to
create a stateful widget you have two
create two classes one for widget itself and
the other to hold the state of the widget.
Consider a simplified widget tree diagram
• Notice the MyHomePage tree node is
connected to the MyHomePageState tree
node. That is show that all StatefulWidget
instances actually have two classes
involved.
Stateful widgets cont…
• It’s important to understand the fact that stateful widgets must have
two classes, one that extends StatefulWidget and the other extends
State. One has immutable data and the other has mutable data
respectively. The diagram below illustrates this concept.
Stateful widget cont…
• Consider the following example
Life cycle methods
Class #1 the class that extends StatefulWidget
createState()
Creates the mutable state for a widget. Every stateful widget should override
this method to return a newly created instance of the associated State
Subclass.
build()
Flutter calls this method when the Widget has to be rerendered (rebuilt).
initState()
This is the first method called after a widget is created.
setState()
Whenever we want to update the state of a widget, setState() should be
called. You call this method to set state in the Widget and ensure it rebuilds
the UI using the ‘build’ method (it’s like a refreshing tool).
Lab Activity: Counter App
• To better understand Statefull
widgets and the different life cycle
methods of widgets we create a
counter app as shown in the
picture.
Listview Widget
ListView is a scrollable list of widgets arranged linearly. It displays its
children one after another in the scroll direction i.e, vertical or horizontal.
There are four options for constructing a ListView, we will look at the three
most common among them:
1. The default constructor takes an explicit List<Widget> of children.
Suitable for list views with a small number of children
Usage Example
ListView(children: <Widget>[Text("List Item 1"), Text("List Item 2"))
2. The [Link] constructor takes a builder, which builds the
children on demand. Suitable for list views with a large (or infinite) number
of children because the builder is called only for those children that are
actually visible.
ListView widget cont…
Usage Example
Final List<int> numbers = <int>[1,2,3,4,5,6];
....
[Link](
itemCount: [Link],
itemBuilder: (BuildContext context, index) {
return Text("List item ${numbers[index]}");
})
List views cont…
3. The [Link] constructor takes two builders: itemBuilder
builds child items on demand and separatorBuilder. Suitable for list
views with a fixed number of children.
Usage Example
Final List<int> numbers = <int>[1,2,3,4,5,6];
[Link](
itemCount: [Link],
itemBuilder: (BuildContext context, index) {
return Text("List item ${numbers[index]}");},
separatorBuilder: (BuildContext context, index) {
return const Divider(); },)
ListView widget cont…
• Basic Properties (Visit [Link] to see more about Container)
Property Purpose Example
scrollDirection The axis along which the scrollDirection:
scroll view scrolls. [Link],
reverse Whether the scroll view alignment:
scrolls in the reading [Link],
direction.
Grid View Widget
• GridView is a widget in Flutter that displays the items in a 2-D
array (two-dimensional rows and columns). As the name suggests, it will
be used when we want to show items in a Grid.
• The Simplest way to create a GridView is through [Link]
constructor.
Usage Example
[Link](
crossAxisCount: 4,
children: [
Text("1"), Text("2"), Text("3"), Text("4"), Text("5"), Text("6")
],
)
Forms and Input
TextField Widget
TextField is the most commonly used text input widget.
Styling a textfield is easy, we just have to provide a decoration property and
supply it with InputDecoration. The example shows a textfield with some
basic styles.
Usage Example:
TextField(
decoration: InputDecoration (
border: OutlineInputBorder(),
hintText: 'Enter a search term’,
),
),
Forms and Input cont…
Form Widget
• The Form widget acts as a container for grouping and validating
multiple form fields.
• The built-in Flutter way to interact with Form is by passing it a key of
type FormState. The widget associates that global key with this
particular form’s state object, giving you access to the state object
anywhere.
Usage Example
Form widget cont…
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(children: [
TextFormField(),
…
ElevatedButton(onPressed: () {}, child: Text("Submit"))
]),
)
Form widget cont…
TextFormField widget
TextFormField wraps a TextField and integrates it with the enclosing Form. This
provides additional functionality, such as validation and integration with other
FormField widgets.
CheckBox
A CheckBox is a stateful widget. changing it state from unchecked to checked means
updating its state.
bool checked = false;
...
Checkbox(value: checked,
onChanged: (bool? value) {
setState(() {checked = !checked;});
}, )
LAB ACTIVITY 1 – GMAIL UI, part 1
Main Task: Develop Gmail
App UI as seen in the
pictures.