Flutter Stateful Widget
Overview
This article will teach you how to build a stateful widget in Flutter. A stateful widget is one with a modifiable state. The status of a widget can vary over its lifespan. This implies that the state of an app may vary with different sets of variables, inputs, and data. Unlike stateless widgets, which must be destroyed and recreated each time we wish to make a change, stateful widgets have mutable states.
Understanding State
We all know that Flutter is all about widgets and that widgets are built using state. So, what exactly is a State? Data is the state. The state is made up of information. This information is used by Flutter to create the user interface. The state is information that may be read synchronously when the widget is constructed and may change over the widget’s lifespan. The widget implementer should guarantee that the State is quickly alerted when such state changes using State.setState. We’re all aware that Flutter is a declarative framework. This means that Flutter creates its user interface to reflect the app’s current state. As a result, whenever the State changes, Flutter must rebuild the UI to reflect the new state. The state is theoretically separated into two kinds in Flutter:
- App State (Global State):
The app State is a kind of Global State. It is also known as the App level state. App State is more intricate than Ephemeral State. It is extensively utilized and may be found on several pages or even a whole app. - Ephemeral State (Local State):
A Local State is an ephemeral state. It applies to a single widget or a subset of the widgets. This status may be properly managed in a specific widget.
Widgets
To develop any Flutter application, we must first create a widget class, which is the foundation of a Flutter program. Flutter creates present-day mobile apps by using widgets. Flutter widgets are divided into two types: stateless widgets and stateful widgets.
Stateless Widget
A stateless widget cannot modify its state while a Flutter application is running. As a result, a stateless widget cannot be repainted while the program is running. As a result, the appearance and features of the widget stay constant during its lifespan. When the component of the UI we're describing doesn't rely on any other widget, stateless widgets can be beneficial. Text, icons, icon buttons, and raised buttons are examples of stateless widgets.
Stateful Widget
When some component of the UI needs to be altered dynamically during runtime, a stateful widget is employed. While the program is active, stateful widgets Flutter can redraw themselves several times. When the section of the UI we're describing changes dynamically, stateful widgets come in handy. A stateful widget Flutter updates itself every time a user hits a button. This is how a stateful widget may be used:
What are Stateful Widgets?
Stateful Widgets Flutter are widgets that can have their state altered after they have been constructed. These states are dynamic, which means they can change multiple times over their lifetime. This essentially implies that the state of an app can change several times depending on numerous factors, inputs, and data. It is used when the user interface may change on the fly. Examples include CheckBox, RadioButton, Form, and TextField. A Stateful Widget Flutter invokes a build function to create its offspring widgets, and the state's subclass keeps the necessary data. It is frequently used when a widget must be redrawn. A state is described as an imperative change in the user interface, while a widget is defined as an immutable description of a part of the user interface. A Stateful Widget may alter if:
- There is a User Input section.
- There is some interaction with the user.
- There have been some Dynamic Changes.
Stateful widgets are helpful when the part of the user interface being described might vary dynamically, for example, due to an internal clock-driven state or based on some system condition. Consider using StatelessWidget for compositions that rely solely on the configuration information in the object and the BuildContext in which the widget is inflated.
Structure of a Stateful Widget
The following code sample depicts a skeleton depiction of a stateful widget using a MyApp subclass. This is a container widget with a property color of red.
Special Methods Associated with Stateful Widget
The Stateful class has several methods to interact with:
BuildContext
It specifies which widget is to be built/re-built and where it will be placed after re-building. As a result, the widget linked with the state is BuildContext.
SetState()
To change the user interface, a State object is utilized. It runs the code for a specific callback and redraws any widgets that rely on that state for configuration.
initState()
A widget's entry point is this procedure. The initState() function initializes all of the procedures on which the build method will rely. This is called just once in the lifespan of a widget and is generally ignored the rest of the time. It must also make a call to super.initState().
didChangeDependencies()
It is used to load the dependencies necessary for state execution. The didChangeDependencies() function is called immediately after the initState() method is called for the first time and before the build method is invoked. Since the build is always called after didChangeDependencies, this is rarely necessary.
dispose()
This function is used to permanently remove an item from the widget tree. It is utilized when we need to free up memory by using super.dispose().
Updating State
setState informs the system that this object's internal state has been modified. The given callback is instantly synchronously invoked. It cannot return a future(the callback cannot be async), as this would make it unclear when the state was truly set. Calling setState informs the framework that the internal state of this object has changed in a way that may influence the user interface in this subtree, causing the framework to schedule a build for this State object. If you just modify the state without executing setState, the framework may fail to schedule a build, and the user interface for this subtree may not be updated to reflect the new state.
Best Practices
Here are some best practices for working with stateful widgets and their methods.
- Keep your widgets as compact as possible. setState causes the widget you're currently in to be rebuilt. If your entire program has only one widget, the entire widget will be recreated, making your app sluggish.
- Use stateful widgets only when necessary. Use stateful widgets only when the widget's state will change in the application.
- In build methods, do not use setState. We should preserve the build method as it is designed to construct the widget tree. Don't do anything fancy here because it will slow down your app. Calls to setState will almost certainly result in subsequent rebuilds, and in the worst-case scenario, you may receive an exception informing you that a rebuild is now in process.
- Complex operations should be avoided. Doing large computations within setState in the stateful widget will prevent your app from recreating the screen.
- Since initState will cause a rebuild after completion, calling setState within this function is unnecessary. This method is used to set state-relevant characteristics such as default values and stream subscriptions.
Conclusion
- Flutter is a declarative framework that creates its user interface to reflect the app’s current state.
- The State is made up of information that can be read synchronously when the widget is constructed and may change over the widget’s lifespan.
- The State is divided into two kinds: App State (Global State) and Ephemeral State (Local State).
- Flutter widgets are divided into two types: stateless and stateful.
- Stateless widgets cannot modify their state while a Flutter application is running, while stateful widgets can redraw themselves several times.
- Stateful widgets are used when the user interface needs to change dynamically during runtime, such as CheckBox, RadioButton, Form, and TextField.
- A stateful widget invokes a build function to create its offspring widgets, and the state’s subclass keeps the necessary data.
- Stateful widgets are useful when the part of the user interface being described might vary dynamically.