Skip to main content

Getting started with state management in Flutter (Part 1)

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.


See this example



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

Popular posts from this blog

Deploy your Flutter app to AppCenter using Fastlane Part 1 (Android)

Deploy your Flutter app to AppCenter using Fastlane Part 1 (Android) Your created a Flutter app on your local machine but how do you share it with the world One of the most satifying feelings is picking up a new technology and building features that work. But now we want to get our app into our user hands. We will eventually want to get our apps live on the app stores for Android and iOS. But first lets deploy our app to a place where our friends can test our app before we get a bunch of negative reviews on the app store. In part one we will set up Fastlane for Android, since Android setup has less steps. Using AppCenter as a testing tool AppCenter , Also known as the "Hockey App", is a tool that is designed for buidling, testing and deploying your mobile applications. In this post we will use AppCenter as the conduent for testing our applications before we deploy our app to the app store. AppCenter gives us the ability to create our own internal "test" app stor

Setting up your development environment for Flutter and Dart with VSCode

I have been working with Flutter for a few years now and have thoroughly enjoyed working with it to build complex UIs effortlessly in mobile and web. Flutter uses Dart as its programming language. Dart is a language that seems to take the best aspects of many programming languages and brings them all together to form an easy-to-use language. Dart is easy and familiar to adopt regardless of your development background or is easy to learn if you are starting out developing for the first time. More to come on Dart in future posts. The Flutter and Dart documentation provided by Google is vast, But with so much documentation out there is it can be hard to know where to start. This is why I am writing this "_getting started_" guide to try to help new developers get started with Flutter. When I am trying to help new brand new developers learn how to work with Flutter and Dart, the constant struggle is getting the development environment setup. My goal with this post is to get y

Getting started with state management in Flutter (Part 2)

Getting started with state management in Flutter (Part 2) Introduction to the Provider package In part 1 of the introduction to state management, we introduced Flutter’s most basic constructs for state management. Using setState() and InheritedWidget 's gave us the ability to control how our application re-draws itself based on state changes in real time. In part 2, we will introduce the Provider package, adding another tool in our toolbox for managing state. Provider gives us "syntactic sugar" on top of the InheritedWidget and gives us an easy to use API that help us to remove the amount of boiler plate code that we have to write which is always a win. Referencing the Provider package in your Flutter application When building Flutter apps we make use of the Dart package management system pub.dev . Pub is very similar to other package managers from other languages. In order to install the Provider package into our project we will need to run the following command