Widgets — Flutter for beginners

Introduction

an application, or a component of an interface, that enables a user to perform a function or access a service : Dictionary

In simpler terms, a widget in flutter is the same as a container. Basically, a clay container that you can change or alter dynamically as per your need with few restrictions. Web developers would be already familiar with the word ‘container’, so it would be easy for them to catch up with the word widget.

Flutter widgets are built using a modern framework that takes inspiration from React. Widgets help you in development of your UI for your app. Moreover, there are a whole lot of widgets that flutter provide which enhances the beauty and User Experience(UX) of your app. Let’s dive deeper!

The Two: Stateful and Stateless

A widget is either stateful or stateless.

  1. Stateful widget: It is dynamic in nature: for example, it can change its appearance in response to events triggered by user interaction or when it receives data. Checkbox, Radio, Slider, InkWell, Form, and TextField are examples of stateful widgets. Stateful widgets subclass StatefulWidget.
Stateful(the user can interact with the screen)

2. Stateless Widget: It never changes. Icon, IconButton, and Text are examples of stateless widgets. Stateless widgets subclass StatelessWidget.

A box(container) with a zoom-in animation

An example of a Stateful Widget is T.V. When I pressed the button the device switches its state from ON -> OFF and OFF -> ON. Moreover, on pressing different numbers I can navigate to the following channels. So here the event triggered is the power button and the response was the T.V switched ON/OFF.

An example of a Stateless widget would be a painting. The painting does not respond to any triggers. You press it, nothing (But don’t press too hard or it will tear up).

Stateful Widget snippet
Stateless Widget
Stateless Widget Snippet

TIP : While working in Android Studio if you type stles you automatically get the option to make a stateless widget and on typing stful you get the option of Stateful widget.

Confusion

A Stateful widget is defined as any widget which changes its state within its lifetime. But it is a very common practice for a StatelessWidget to have a StatefulWidget as one of its children. Doesn’t StatelessWidget become stateful if it has StatefulWidget as one of its children?

Widget Tree

Solution

A StatelessWidget will never rebuild by itself (but can from external events or triggers). A StatefulWidget can. That is the golden rule.

Stateless only means that all of its properties are immutable and that the only way to change them is to create a new instance of that widget. It doesn’t e.g. lock the widget tree.

Thanks for reading. I will be posting about all the Widgets in detail. Also, you can follow me on LinkedIn

References

Flutter | Google Actions | Gluster