Provider in Flutter for global state: solved exercise

  2 minutes

If you are looking for Provider in Flutter, this solved exercise gives you a practical implementation pattern you can reuse in real projects.

Build a screen with:

  • create a shared counter store
  • read state from multiple widgets
  • update state globally
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (_) => CounterStore(),
      child: const MaterialApp(home: ProviderPage()),
    ),
  );
}

class CounterStore extends ChangeNotifier {
  int value = 0;

  void increment() {
    value += 1;
    notifyListeners();
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Provider basico')),
      body: Center(
        child: Consumer<CounterStore>(
          builder: (_, store, __) => Text('${store.value}', style: const TextStyle(fontSize: 42)),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => context.read<CounterStore>().increment(),
        child: const Icon(Icons.add),
      ),
    );
  }
}

All subscribed widgets react to state changes after notifyListeners.

  • Calling notifyListeners too often.
  • Putting all app state in one provider.
  • Coupling UI and business logic.

A stable state-management baseline for many small and medium Flutter apps.

Yes, in many projects when state boundaries are well-defined.

When you need stricter architecture, tracing, or advanced testing workflows.

Not if you split state and rebuild only what is needed.