DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Guide for Voice Search Integration to Your Flutter Streaming App
  • Why Choose Flutter App Development When You Need a Mobile App
  • Cross-Platform Mobile Application Development: Evaluating Flutter, React Native, HTML5, Xamarin, and Other Frameworks
  • Weighing the Trade-Offs of Native vs. Cross-Platform Mobile App Development

Trending

  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • How Kubernetes Cluster Sizing Affects Performance and Cost Efficiency in Cloud Deployments
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • How to Merge HTML Documents in Java
  1. DZone
  2. Coding
  3. Frameworks
  4. Flutter 2.0 State Management Introduction With Provider 5.0

Flutter 2.0 State Management Introduction With Provider 5.0

New Flutter developers need to understand state management in order to build more complex applications with multiple screens and data storage options.

By 
Craig Oda user avatar
Craig Oda
DZone Core CORE ·
May. 01, 21 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
14.3K Views

Join the DZone community and get the full member experience.

Join For Free

With Flutter 2.0, you can build apps on mobile, web and desktop.  Graphics performance is fantastic and the development tools are great. The main barrier to learning Flutter is an understanding of state management.  This tutorial covers the Provider package, one of the most popular and easiest tools to manage state in Flutter.

Windows Desktop, Mobile and Web Displays

A video version of this tutorial is available. Code and image files are on GitHub. 

When to Use Provider

If your application is on a single screen with limited interaction with outside data sources and APIs, you should use the built-in setState method of Flutter.  You do not need to use a provider for simple applications.  If your application has multiple screens with multiple API calls, you should use the provider.

How Provider Works

Provider makes it easier to set widgets to listen a variable and wait for a change. You can also use the provider to send a notification to a listener when data changes.

For our simplified example, we have two screens. The first screen is a list of thumbnails.

List of Thumbnails

Each thumbnail is 9KB with a size of 320x160.  The thumbnails are designed to be fast to load over a network.  To make the tutorial easier, the thumbnails and full-size images are stored locally.  The thumbnails and images are in equirectangular format to provide a virtual 360°  experience. When a thumbnail is tapped, the application goes to another screen that displays a full-size image with 360° navigation.

Full-sized Image with 360 Navigation

ChangeNotifier and notifyListeners

The core concept of a provider is that a widget listens for changes.  To help manage the changes and notifications to the listeners, we use the ChangeNotifer Flutter class.  In the example below, the class ImageNotifier manages changes to a variable called image.

Dart
 




x
15


 
1
import 'package:flutter/material.dart';
2

          
3
class ImageNotifier extends ChangeNotifier {
4
  Image _image = Image.asset('assets/images/R0011911.JPG');
5

          
6
  // getter
7
  Image get image => _image;
8

          
9
  // update
10
  void updateImage(Image image) {
11
    _image = image;
12
    notifyListeners();
13
  }
14
}
15

          



When a person presses the thumbnail button on screen 1, the updateImage() method is run. On screen 2, the image is displayed with the getter image.

ChangeNotifierProvider

Up to this point, we haven't used provider.  ChangeNotifier is built into Flutter.

Our first step to using a provider starts in the main() method.  It's the first thing you run in runApp(). In the main.dart file, we need to wrap ChangeNotifierProvider around your main app.  I've called the main app MyApp().

Dart
 




xxxxxxxxxx
1
12


 
1
import 'package:thumb_1/image_notifier.dart';
2
import 'thumb_screen.dart';
3
import 'package:provider/provider.dart';
4

          
5
void main() {
6
  runApp(
7
    ChangeNotifierProvider(
8
      create: (_) => ImageNotifier(),
9
      child: MyApp(),
10
    ),
11
  );
12
}



Change, Notification, and Provide

Let's review the core concepts up to this point.

  1. Data changes.  In our example, we're changing an image. The change starts by clicking on the thumbnail.  The image variable is changed with the updateImage() method we created.
  2. Create a notification of the change. In our example, our notification is that the full resolution image has changed. The notification is created with notifyListeners() which is also in the updateImage() method.
  3. Provide the notification to the widgets that are listening for the specific change.

Although these concepts are fairly easy to understand, it is different from a procedural programming paradigm.

Procedural Process

Let's look at an alternative process with psuedo-code.

On screen 1

buttonPress(image=imageName) 

On screen 2

displayImage(imageName)

The process above is easier to understand for simple applications.  It becomes increasingly difficult to manage as the application gets more complex.

Provider Process

The provider process adds a few additional steps. More importantly, it requires a change in thinking about how the image is displayed.  Instead of the button changing the imageName variable in screen 2 directly, the button talks to an intermediary that sends a notification to any widget that has subscribed to the change.

Screen 1

buttonPress(updateImage(imageName))

Change Notification Manager

updateImage(imageName)

notifyListeners(imageName)

Screen 2

displayImage(imageName)

Updating the Image

From screen 1, we need to call the updateImage() method.  The code may look a bit confusing at first, but you'll quickly get used to it with just a little bit of practice.

context.read<ImageNotifier>().updateImage(...

ImageNotifier is the name of the class we created that extends ChangeNotifier, which is built into Flutter.

The full code for the widget of the thumbnail is shown below.

Dart
 




x


 
1
import 'package:flutter/material.dart';
2
import 'package:thumb_1/details_screen.dart';
3
import 'package:provider/provider.dart';
4
import 'package:thumb_1/image_notifier.dart';
5

          
6
class CarThumbButton extends StatelessWidget {
7
  const CarThumbButton(
8
      {Key? key, required this.imageNameBase, required this.toolTip})
9
      : super(key: key);
10

          
11
  final String imageNameBase;
12
  final String toolTip;
13

          
14
  @override
15
  Widget build(BuildContext context) {
16
    return IconButton(
17
      icon: Image.asset('assets/images/$imageNameBase\_THUMB.jpg'),
18
      iconSize: 300,
19
      onPressed: () {
20
        context.read<ImageNotifier>().updateImage(
21
              Image.asset('assets/images/$imageNameBase.JPG'),
22
            );
23
        Navigator.push(
24
            context, MaterialPageRoute(builder: (context) => DetailsScreen()));
25
      },
26
      tooltip: this.toolTip,
27
    );
28
  }
29
}
30

          



Displaying the Image

The image is displayed with a similar process of reading from the context.

context.read<ImageNotifier>().image

The last word in the line, image, is the getter from ImageNotifier.

I've wrapped the image in Panorama() to get the 360° navigation.

Dart
 




xxxxxxxxxx
1
19


 
1
import 'package:flutter/material.dart';
2
import 'package:panorama/panorama.dart';
3
import 'package:thumb_1/image_notifier.dart';
4
import 'package:provider/provider.dart';
5

          
6
class DetailsScreen extends StatelessWidget {
7
  @override
8
  Widget build(BuildContext context) {
9
    return Scaffold(
10
      appBar: AppBar(),
11
      body: Center(
12
        child: Panorama(
13
          child: context.read<ImageNotifier>().image,
14
        ),
15
      ),
16
    );
17
  }
18
}
19

          


Running the Code

You need to have Flutter 2.0 and Dart 2.12. 

Shell
 




xxxxxxxxxx
1


 
1
git clone https://github.com/codetricity/theta_provider_tutorial
2
cd .\theta_provider_tutorial\
3
flutter pub get
4
flutter create .
5
flutter run



Select the Device

Note, to run Windows, you will need Visual Studio (not just VS Code) installed.  To run macOS and iOS, you'll need XCode.  To run Android, you need an Android Virtual Device.  The easiest way to get the AVD is to install Android Studio.

Select the Device

Desktop App

More information on building for Windows desktop is available in my previous DZone article, Build Great Windows Desktop Apps With Flutter.

To quickly gain practice modifying the example code for this tutorial, you can add a new variable to image_notifier.dart.

Remember to add the following for each new variable:

  1. Private variable initialization.  Note that the example uses Dart 2.12 with sound null safety. You need to assign a default value to all variables or explicitly tell dart the variable can be null.  You cannot do something like String _caption;
  2. Getter.
  3. Setter with notifyListeners.

image_notifier.dart Screenshot

If you prefer to start with a completely blank editor and a new Flutter project, go through the steps in the video I mentioned at the start of the article.

Other State Management Techniques

There are many other Flutter state management techniques.  Refer to the Flutter official documents for more options.  Provider is a great way for you to get started.

Summary

Flutter is a wonderful framework for rapidly building mobile, desktop, and web apps.  There are many options for state management.  If your app has more than a few screens and data storage options, you should use a state management package instead of relying on setState(). Provider is one of the most popular packages for state management.  It's easy to use once you understand the process of making a change, creating a notification of the change, providing the change, and listening for the change.

The best way to really understand the concept of state management is to implement it.  Open up VS Code and starting coding right now!


Flutter (software) mobile app

Opinions expressed by DZone contributors are their own.

Related

  • Guide for Voice Search Integration to Your Flutter Streaming App
  • Why Choose Flutter App Development When You Need a Mobile App
  • Cross-Platform Mobile Application Development: Evaluating Flutter, React Native, HTML5, Xamarin, and Other Frameworks
  • Weighing the Trade-Offs of Native vs. Cross-Platform Mobile App Development

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!