Flutter provider without context

Flutter Provider without Context

The Provider package in Flutter is a state management solution that allows you to easily share and access state across different parts of your application. By default, the Provider package requires the use of the ‘BuildContext’ to provide and consume state. However, there are scenarios where you might want to access or update state without having direct access to the ‘BuildContext’, such as in model classes or utility functions.

To use Provider without the ‘BuildContext’, you can make use of the ‘ProviderContainer’ class provided by the ‘provider’ package. This class allows you to store and access state without the need for a ‘BuildContext’ object.

Example:

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

  class CounterModel {
    int counter = 0;

    void incrementCounter() {
      counter++;
    }
  }

  void main() {
    runApp(
      ChangeNotifierProvider(
        create: (context) => CounterModel(),
        child: MyApp(),
      ),
    );
  }

  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text('Provider without Context'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Consumer(
                  builder: (context, counterModel, child) {
                    return Text(
                      'Counter: \${counterModel.counter}',
                      style: TextStyle(fontSize: 20),
                    );
                  },
                ),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    // Increment counter without context
                    ProviderContainer()
                        .read()
                        .incrementCounter();
                  },
                  child: Text('Increment Counter'),
                ),
              ],
            ),
          ),
        ),
      );
    }
  }
  
  

In the example above, we have a simple application with a counter state managed by the ‘CounterModel’ class. The ‘CounterModel’ class is a basic implementation of the ‘ChangeNotifier’ class provided by the Provider package. It contains a ‘counter’ property and a ‘incrementCounter’ method to update the counter value.

The ‘ChangeNotifierProvider’ is used to wrap the main application (‘MyApp’) with an instance of ‘CounterModel’. This provides access to the ‘CounterModel’ instance to all the widgets within the app.

The ‘Consumer’ widget is used to listen to changes in the ‘CounterModel’ and rebuild the UI whenever the counter value changes. Inside the ‘Consumer’ widget, the counter value is accessed using the ‘counterModel’ parameter.

To increment the counter without using the ‘BuildContext’, we make use of the ‘ProviderContainer’ class. The ‘read’ method of ‘ProviderContainer’ is used to access the ‘CounterModel’ instance, and we can then call the ‘incrementCounter’ method to update the counter value.

By utilizing the ‘ProviderContainer’ class, we can maintain separation between the UI components and the state, allowing for easier testing and refactoring of the code.

Leave a comment