State Management in Flutter with Provider Package: Simplify Your App's Architecture

 This is a Flutter application that demonstrates the use of the Provider package for state management. The main function runs the MyApp widget, which sets up the ChangeNotifierProvider and the MaterialApp widget. The ChangeNotifierProvider creates a new instance of the MyHomePageController and makes it available to the widget tree as a provider. 


The MyHomePage widget is the main screen of the application and displays a counter that can be incremented by tapping on the floating action button. It receives the MyHomePageController instance from the provider using the Provider.of method and passes it to a Consumer widget that rebuilds only the child widget when the counter value changes. The MyHomePageController extends ChangeNotifier and contains the logic for incrementing the counter and notifying the listeners of the change.

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<MyHomePageController>(
      create: (_) => MyHomePageController(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {
    final controller = Provider.of<MyHomePageController>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Consumer<MyHomePageController>(
              builder: (context, controller, _) => Text(
                '${controller.counter}',
                style: Theme.of(context).textTheme.headline6,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => controller.incrementCounter(),
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

class MyHomePageController extends ChangeNotifier {
  int _counter = 0;

  int get counter => _counter;

  void incrementCounter() {
    _counter++;
    notifyListeners();
  }
}

Comments

Popular posts from this blog

Error Handling in Flutter - Gradle issue

How to Make a Dynamic and Trending ListView with Flutter Widgets?

Understanding API integration with Getx State management