Getting started with state management in Flutter (Part 1)
Introduction
Flutter is great for making beautiful cross-platform UIs with its everything is a widget concepts. But how do you actually move data around your application. State management is a huge part of any good application. State management is critical to providing a pleasurable user experience. We are going to dive into some of the basic state management concepts.
Shift your design thinking to be declarative
A huge paradigm shift when working in Flutter is thinking declaratively. The way most of our brains work make it easy to understand imperative programming concepts. When our code is organized as sequential steps we can follow the code for one branch of code to the next. When programming declaratively we describe what needs to be done and our system responds based on the action we describe.
What does this mean for Flutter?
In Flutter we describe what should be done in our app and Flutter responds by drawing our application on the screen based on the current state of data in our application.
Don’t be afraid to re-draw
Now that we are thinking declaratively. What happens when we need to change the state of our application? Showing a loading spinner? Letting a user know they missed a required field?
Flutter is designed to be reactive to state changes. Any time Flutter detects that your state has been changed you application will re-draw itself based on the current state of data.
Flutter is really fast so don't worry that you app needs to re-draw itself. I have not seen any lag in the UI for the Flutter apps that I have built so far. And there are many ways that we can optimize which widgets and elements are re-drawing and when.
When re-drawing we can target full pages, parts of pages or even single elements. This allows us to be very specific about which data should change and when.
A look at Flutter Ephemeral State
What is Ephemeral State
As a self-taught developer Ephemeral is a word that I had to look up because it had not come up in my learning up to this point in my career. The definition is Ephemeral is lasting for a very short time. So in context of speaking about your app your ephemeral state will be the state of your app that you do not expect to manage for the life of your app. Instead this is state that lives for short periods of time.
This is something that we use time and time again in the applications that we will build. Ephemeral state will be essential to making sure that you users have a responsive experience while working in your application.
Lets look at an example
For example, imagine that you have a form the needs to be submitted.
You have a few form fields with a button. When we click on the button we expect for that button to be disabled while we are submitting the form.
In order to manage the state of the button we decide to define a boolean value defined as isLoading
.
When isLoading
is false
we enable the submit button and a Text
widget is shown with “Login”, when true
the text of the button will be hidden and a CircularProgressIndicator
will be shown inside of the button.
When we call setState we are telling Flutter that some data has changed and I need you to re-draw this widget to reflect that our state has changed to be "Loading"
We don't want our user to be able to click the login button again while we are validating their access.
In order to make the button not clickable we have to return null
from the onTapped
event on the button we will also switch on the state of our isLoading
variable that we have been tracking to determine if the user should be able to click the button again.
But what about when I need to keep track of some global state? Lets talk App State
App State comes a little more natural to me. One of the most conscious decisions that you need to make in your application are related to how to manage state that lives during a single session or over multiple sessions. Your users will expect that they should have to start from scratch ever time that that change pages in you app.
In the case where your user leaves you application and come back they expect that you will remember them. If you remember the old school Atari or Nintendo you had to beat the game in one session or you had to start over again. We don't want our users to experience that type of pain :).
Earlier we looked at our form submission ephemeral use case where we were managing the state of the button itself. Now let's expand on that and understand when we may use app state for our form.
Our form will be using our username and password field to simulate a login process. Once the user is authenticated we will return an access token that will be used during our "session to verify that our user has access data within our app.
We need to store our token in app state vs ephemeral state so that we have access to our access token across many widgets in our application.
We will build a class (AppBloc
) that inherits from InheritedWidget
and manages our token during our “session”.
Each time we make a call to get data for our app we will pass the token
that we retrieved from our state and send it to our data access layer where the user is validated before returning data.
In the Red Section we see the function that run when our user presses the button. We start our spinner, run our authenticate method and once complete we stop our loader.
In the Blue section we have a conditional where we show/hide our spinner and button text based on whether we are loading of not. An if we fail authentication we will show a text label informing our user that "Login Failed." We will get more complex but hopefully this illustrates how we can user state to manage our application
Whats next?
In conclusion, state is one of those things that are at the core of any application we build. It doesn't matter what method of state management that you use. What really matters is that you understand the decision behind when to use the types of state within you app. It will help you app become more maintainable as your state management design builds consistency.
Other options for State Management
We have now learned the difference between different types of state for your Flutter applications and when to use them.
We saw some examples of constructs that help us manage state. StatelessWidget
, InheritedWidget
, and Bloc
. Over the next several posts we will cover these topics in more depth. We are just touching the tip of the iceberg of state management concepts.
Here is a subset of popular ways that Flutter state is managed:
- setState
- InheritedWidget
- The Bloc pattern
- Provider
- Redux
- …
Comments
Post a Comment