Flutter Playground – Part 3: Widgets

In the previous post, we saw how to create the layout of a basic login screen. However, all the code was written in a single file. Also, all the styles for various widgets were written inline. Before we delve into creating other complex widgets and widget classes, let’s try and understand what exactly are widgets and how do they work in the flutter world.

In this post, we will study the 2 categories of widgets: Stateless and Stateful widgets.

What are Widgets?

A widget is an immutable description of part of a user interface.

Flutter widgets are built using a modern react-style framework, which takes inspiration from React. The central idea is that you build your UI out of widgets. Widgets describe what their view should look like given their current configuration and state. When a widget’s state changes, the widget rebuilds its description, which the framework diffs against the previous description in order to determine the minimal changes needed in the underlying render tree to transition from one state to the next.

https://flutter.io/docs/development/ui/widgets-intro

Any UI element that you wish to render is essentially a widget, either a Stateless or a Stateful one. A complex UI will have dozens of widgets, that can be nested within each other by using different kinds of layouts, which are again widgets themselves.

Sample widget tree in Flutter

Most widgets have the build() method, which is responsible to instantiate and return the widget which can be rendered. Most of your widget’s state will be managed and handled inside this method. build() method can be called multiple times during the lifecycle of a widget, and thus, it becomes important that the code contained in this method is optimised.

1. Stateless widgets

Stateless widgets are screen elements in flutter that do not require a mutable state. They are useful when the internal state of the widget does not depend on any external variables or factors, apart from the intial state or configuration provided during its creation.

Examples

2. Stateful widgets

Stateful widgets are, as the name suggests, depends on a ‘State’, which can be provided during the initialization or which can change during the lifetime of the widget. Thus, when a part of the UI can change dynamically, Stateful widgets are helpful.

Stateful widget instances are immutable, however, they store their mutable state by using the State class. When the state of a widget changes, the widget itself reads the latest state information, and adapts or changes the UI of the widget.

Examples

Posts in this series:

Previous post: Flutter Playground – Part 2: Login screen

Leave a Reply

Your email address will not be published. Required fields are marked *