Widgets in Flutter — Flutter Basic Programming — Part 3

Hoang Nguyen
5 min readApr 27, 2022

--

Hello guys, in previous story i’ve talk about installation in Flutter to prepare for today topic so that finally we can start to write code with Flutter. If you aren’t set up environment, please check previous story about Flutter Installation. And now let’s FlutterWithMe!

In Flutter, everything is a widget

Widget tree
  • In flutter, Widget is a way to declare and construct UI.
  • Widget is not just a piece of UI. Widget is a lot more than just structural elements like buttons, text, image, list or slider. A widget might display Something, it might help define design, it might help with layout, it may handle user interaction, etc.
  • Widget is look like a blueprint for displaying your app state, and Flutter using these blueprint to create views.
Example display text “Hello Widget” in Flutter
Text(
'Hello Widget',
style: Theme.of(context).textTheme.headline4,
);
  • A widget is an immutable description of part of a user interface.

But, how Flutter draw a widget into screen ?

Flutter using build() method to describes the part of the user interface represented by this widget.

This method will be called on these conditions:

Conditions to called build() method

You can see that “State” keyword is main point here, but what’s State ?

  • State can be described as “whatever data you need in order to rebuild your UI at any moment in time”.
  • When the state of your app changes (for example, the user flips a switch in the settings screen), you change the state, and that triggers a redraw of the user interface.
  • State can be separated into two concept: Ephemeral state and App state.

Ephemeral state

  • Called UI state or local state. Which you can neatly contain in a single widget.
  • No need to use state management techniques on this kind of state, only need using “Stateful Widget”.
  • Only need to use setState() to alter your current state.
Counter example
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}}

Because nowhere need access to_index variable, and it’s only worked inside _MyHomePageState so it won’t mind that _index will change back to zero.

App state

  • Called shared state. Use when you want to share across many parts of your app or want to keep between user sessions.For example, these case will using application state:
  1. User preferences.
  2. Login information
  3. Shopping cart from e-commerce
  4. Notification from social app
  • For manage app state, there are many ways to manage it with techniques is “state management” like Provider, Bloc, …

Widget tree, Element tree and Render tree

  • Widget will describes the configuration for an Element.
  • Element is an instantiation of a Widget at a particular location in the tree.
  • RenderObject will handles size, layout and painting.
Three objects in each widget

So, when you app start, Flutter will:

  1. Go through your widgets and create Widget tree.
  2. Corresponding to the Widget tree, creates the Element tree in which each Element object is created by calling createElement() on the widget.
  3. Each render object will be created when Element calls createRenderObject().
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Container(
key: _keyRed,
width: 375.w,
height: 500.h,
color: Colors.red,
child: Text(
"Screen Width : ${ScreenUtil().screenWidth} Height : ${ScreenUtil().screenHeight}"
"\n$_containerSize "
"\nWidth Ratio : ${ScreenUtil().scaleWidth} "
"\nHeight Ratio : ${ScreenUtil().scaleHeight} "
"\nText Ratio : ${ScreenUtil().scaleText} "
"\n$defaultTargetPlatform",
style: AppTextStyle.label3,
),
),
Text(
"Aspect Ratio : ${ScreenUtil().pixelRatio}",
style: AppTextStyle.label3,
),
],
),
);
}

And this is where it’s look like in Flutter Inspector.

Now we will explain a little bit about three trees in Widget.

Widget Tree

  • Basiclly it’s all of Widget that we created when coding. For example: Text, Column, Image,… All of nested widget will create a widget tree.
  • We can fully control widget tree because we are the one who build the position of widget in this tree.
  • Widget tree will created when build() method called.
  • Widget tree not only display view in screen but also it’s help Flutter know that which will draw in screen. Widget tree will rebuild frequently.

Element Tree

  • Will linked with Widget tree. It’s information that will set with object/element which displayed. It’s rarely rebuild.
  • Will manage with another way and don’t rebuild when build() method called.
  • Flutter will automatically create an element in each Widget in Widget Tree. It’ll process immediately when Flutter handle Widget first time.
  • We can said that one element is one object that will manage in heap memory by Flutter, it’s related to Widget in Widget tree.
  • Element only keep one reference to Widget in Widget tree.

=> So that, when Flutter saw a stateful widget, it’ll create element and call createState() method to create new state object base on state class. And with that, “State” is a single object in Stateful Widget that linked with Element (in Element tree) and Widget (in Widget tree).

Render tree

  • It’s represent for which element/object that display on screen.
  • It’s rarely rebuild.
  • It’ll linked with Element Tree.Element in Element Tree will point to render object which actually display in view.
  • Whenever Flutter saw an element that haven’t render before, it’ll reference to Widget in Widget Tree, and create an element in Element Tree.
  • Flutter also have layout phase, on this phase it’ll calculate and get space, layout display in screen.
  • It’s also have another phase for configuration listeners with Widget that let us handle event.

It’s too long to talk about Widget and State in this story. In next story i’ll talk about widget type and some basic widget in Flutter, so keep watching. Thanks for your time!

--

--

Hoang Nguyen
Hoang Nguyen

Written by Hoang Nguyen

I've started with Flutter since 2019 and have good knowledge about Flutter and some architecture. I want to share more of my knowledge and learn more from other

No responses yet