Simplify State Management with Provider in Flutter
Tags: flutter, android, programming, beginners
Published: 2023-09-24 12:30:00

In this blog post, we'll explore how to implement state management using the Provider package in Flutter. To illustrate this, we'll create a Voting Age Calculator application. This app will help users determine if they are eligible to vote based on their age.

Introduction to Provider
Provider is a versatile state management solution for Flutter. It offers a straightforward and efficient way to manage and share application state. Let's dive into how you can use Provider for your Flutter projects.

What is Provider and Why Should You Care?
Provider is a state management library for Flutter that makes managing and sharing your app's state a breeze. It's easy to understand and integrate into your projects, making your code more organized and efficient.

Here's why you should care about Provider:

Simplicity: Provider simplifies state management, especially when compared to other approaches like InheritedWidget or Redux.

Scalability: It's suitable for both small apps and large, complex ones. You won't outgrow Provider.

Widget Rebuild Optimization: Provider automatically optimizes widget rebuilds, improving performance.

Widely Adopted: Provider is well-supported by the Flutter community and is used in many open-source packages.

Now that we understand why Provider is awesome, let's see how we can implement it.

Setting Up the Provider
First, ensure you have the Provider package added as a dependency in your pubspec.yaml:

```
dependencies:
  flutter:
    sdk: flutter
  provider: ^6.0.5  # Use the latest version

```
Creating the Model
In Flutter, the model represents the data you want to share across your app. In our case, the model will store the eligibility message and a boolean value indicating whether the user is eligible to vote.

```
class EligibilityScreenProvider extends ChangeNotifier {
  String _eligibilityMessage = "";
  bool _isEligible = false;

  // Check eligibility based on age
  void checkEligibility(int age) {
    if (age >= 18) {
      eligibleForVoting();
    } else {
      notEligibleForVoting();
    }
  }

  // User is eligible for voting
  void eligibleForVoting() {
    _eligibilityMessage = "You are eligible for Voting";
    _isEligible = true;
    notifyListeners();
  }

  // User is not eligible for voting
  void notEligibleForVoting() {
    _eligibilityMessage = "You are not eligible for Voting";
    _isEligible = false;
    notifyListeners();
  }

  String get eligibilityMessage => _eligibilityMessage;
  bool get isEligible => _isEligible;
}

```
Building the User Interface
Now that we have our data model set up, let's create the user interface. We'll design a simple form where users can enter their age and check their eligibility to vote.

```
class Voting extends StatefulWidget {
  const Voting({super.key});

  @override
  State<Voting> createState() => VotingState();
}

class VotingState extends State<Voting> {
  final votingAge = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<EligibilityScreenProvider>(
      create: (context) => EligibilityScreenProvider(),
      child: Builder(builder: (context) {
        return Scaffold(
          body: Container(
            padding: const EdgeInsets.all(16),
            child: Form(
              child: Consumer<EligibilityScreenProvider>(
                builder: (context, provider, child) {
                  return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: (provider.isEligible == null)
                              ? Colors.grey
                              : provider.isEligible
                                  ? Colors.green
                                  : Colors.red,
                        ),
                        height: 50,
                        width: 50,
                      ),
                      const SizedBox(height: 16),
                      TextFormField(
                        controller: votingAge,
                        decoration:
                            const InputDecoration(hintText: "Enter your age"),
                      ),
                      const SizedBox(height: 16),
                      SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          onPressed: () {
                            final int age = int.parse(votingAge.text.trim());
                            provider.checkEligibility(age);
                          },
                          child: const Text("Check if you can vote"),
                        ),
                      ),
                      const SizedBox(height: 16),
                      Text(provider.eligibilityMessage)
                    ],
                  );
                },
              ),
            ),
          ),
        );
      }),
    );
  }
}

```

Running the Application
In the main.dart file, we simply set up the application theme and set the Voting widget as the home screen.

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      debugShowCheckedModeBanner: false,
      home: const Voting(),
    );
  }
}

```
Conclusion
By following this guide, you've learned how to implement state management using the Provider package in Flutter. We built a Voting Age Calculator application that demonstrates how Provider can simplify state management and make your Flutter development journey smoother.

Sharing is caring! If you found this guide helpful, don't forget to share it with your fellow Flutter developers. Happy coding! ✨

#FlutterDev #Provider #StateManagement #FlutterState #MobileAppDevelopment

Video: https://youtu.be/kr9hE-CfY3Y