Find The Latest Tech Insights, News and Updates to Read

Understanding the Concept of Providers in Flutter

Written by Achin Verma | Oct 19, 2023 6:53:39 PM

Introduction

In Flutter, a "provider" refers to a design pattern and a package that helps manage state in your application. It's commonly used to efficiently share and update data between different parts of your app, such as widgets, without the need for prop drilling (passing data through multiple widget layers).

The "provider" package in Flutter provides a way to manage and consume data using a provider class, which acts as a source of truth for your app's state.

Let's go through the concept of providers step by step with an example:

Step 1: Setting up the Project

Assuming you have Flutter and Dart installed, start by creating a new Flutter project:

 

flutter create provider_example
cd provider_example

 

Open the pubspec.yaml file of your project and add the following dependency under the dependencies section:

dependencies:
  flutter:
    sdk: flutter
  provider: ^5.0.0

 

Then, run flutter pub get to install the package.

Step 2: Creating a Data Model

Create a file named user.dart inside the lib folder of your project. This file will define a simple User data model:

 

class User {
  final String name;
  final int age;

  User(this.name, this.age);
}


Step 3: Creating a Provider

Create a file named user_provider.dart inside the lib folder. This file will define a provider class using the ChangeNotifier class from the provider package:

 

import 'package:flutter/material.dart';
import 'user.dart';

class UserProvider extends ChangeNotifier {
  User _user;

  User get user => _user;

  void updateUser(String name, int age) {
    _user = User(name, age);
    notifyListeners(); // Notify listeners that the data has changed
  }
}


Step 4: Using the Provider in Widgets

Create a file named main.dart inside the lib folder. This file will demonstrate how to use the UserProvider in your app:

 

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'user_provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => UserProvider(),
      child: MaterialApp(
        title: 'Provider Example',
        home: HomeScreen(),
      ),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final userProvider = Provider.of<UserProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Provider Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Name: ${userProvider.user?.name ?? 'N/A'}'),
            Text('Age: ${userProvider.user?.age ?? 'N/A'}'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                userProvider.updateUser('John Doe', 30);
              },
              child: Text('Update User'),
            ),
          ],
        ),
      ),
    );
  }
}

 

Step 5: Running the App

Run the app using flutter run in your terminal. You should see the app with the "Name" and "Age" fields displayed as "N/A" initially. When you click the "Update User" button, the user's data should update accordingly.

In this example, we've created a simple user data model and a UserProvider class that extends ChangeNotifier. We've then used the ChangeNotifierProvider widget to provide the UserProvider instance to the widget tree. Finally, we've consumed the provided data using the Provider.of method in the HomeScreen widget.

Remember that this is just a basic example. In real-world applications, you can use providers to manage more complex state and data throughout your app.

Ready to take your Flutter development to the next level? Dive deep into the world of providers and supercharge your app's state management! Hire Flutter Developers and get started today!