Flutter provider reset state

To reset the state of a Flutter Provider, you can use various approaches depending on the specific use case. Below, I will explain a couple of methods with examples.

Method 1: Using a ResetNotifier class

One way to reset the state of a Provider is by creating a ResetNotifier class that extends the ChangeNotifier class provided by the Flutter framework. This class will handle the state management and provide a method to reset the state.


  import 'package:flutter/foundation.dart';
  
  class ResetNotifier extends ChangeNotifier {
    int _counter = 0;
  
    int get counter => _counter;
  
    void incrementCounter() {
      _counter++;
      notifyListeners();
    }
  
    void resetCounter() {
      _counter = 0;
      notifyListeners();
    }
  }
  

In the above example, we have created a ResetNotifier class with a counter variable. The incrementCounter method increments the counter, while the resetCounter method resets it to zero. The notifyListeners method is called to notify any listeners of the state change.

To use this ResetNotifier class in your application, you can wrap the widget tree with a ChangeNotifierProvider and provide an instance of the ResetNotifier class.


  import 'package:flutter/material.dart';
  import 'package:provider/provider.dart';
  
  void main() {
    runApp(MyApp());
  }
  
  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return ChangeNotifierProvider(
        create: (_) => ResetNotifier(),
        child: MaterialApp(
          home: MyHomePage(),
        ),
      );
    }
  }
  
  class MyHomePage extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      final resetNotifier = Provider.of(context);
  
      return Scaffold(
        appBar: AppBar(
          title: Text('Reset State Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Counter: ${resetNotifier.counter}',
                style: TextStyle(fontSize: 24),
              ),
              SizedBox(height: 16),
              RaisedButton(
                child: Text('Increment Counter'),
                onPressed: resetNotifier.incrementCounter,
              ),
              RaisedButton(
                child: Text('Reset Counter'),
                onPressed: resetNotifier.resetCounter,
              ),
            ],
          ),
        ),
      );
    }
  }
  

In the example above, we have wrapped the MyApp widget with ChangeNotifierProvider, passing the ResetNotifier as the value for the create parameter. Inside the MyHomePage widget, we can now access the ResetNotifier using the Provider.of method.

The resetNotifier object gives us access to the counter variable and the incrementCounter and resetCounter methods. We can display the value of the counter variable using the Text widget. The RaisedButton widgets are used to trigger the incrementCounter and resetCounter methods when pressed.

Method 2: Using Provider.of(context, listen: false)

Another way to reset the state without using a dedicated ResetNotifier class is by directly using the Provider.of method with the listen parameter set to false.


  import 'package:flutter/material.dart';
  import 'package:provider/provider.dart';
  
  void main() {
    runApp(
      ChangeNotifierProvider(
        create: (_) => CounterProvider(),
        child: MyApp(),
      ),
    );
  }
  
  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: MyHomePage(),
      );
    }
  }
  
  class MyHomePage extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Reset State Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Consumer(
                builder: (context, counterProvider, _) => Text(
                  'Counter: ${counterProvider.counter}',
                  style: TextStyle(fontSize: 24),
                ),
              ),
              SizedBox(height: 16),
              RaisedButton(
                child: Text('Increment Counter'),
                onPressed: () {
                  Provider.of(context, listen: false)
                      .incrementCounter();
                },
              ),
              RaisedButton(
                child: Text('Reset Counter'),
                onPressed: () {
                  Provider.of(context, listen: false)
                      .resetCounter();
                },
              ),
            ],
          ),
        ),
      );
    }
  }
  
  class CounterProvider with ChangeNotifier {
    int _counter = 0;
  
    int get counter => _counter;
  
    void incrementCounter() {
      _counter++;
      notifyListeners();
    }
  
    void resetCounter() {
      _counter = 0;
      notifyListeners();
    }
  }
  

In this example, we have created a CounterProvider class that extends ChangeNotifier. The CounterProvider class has the same counter, incrementCounter, and resetCounter methods as the previous ResetNotifier class. However, this time we directly use the Provider.of method within the MyHomePage widget to access the CounterProvider.

Inside the RaisedButton widgets, we call the incrementCounter and resetCounter methods using Provider.of(context, listen: false). The listen parameter set to false ensures that the widget does not rebuild when the state changes.

Leave a comment