Provider in Flutter for global state: solved exercise

Provider in Flutter for global state: solved exercise

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

Problem statement

Build a screen with:

  • create a shared counter store
  • read state from multiple widgets
  • update state globally

Flutter solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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),
      ),
    );
  }
}

Expected result

All subscribed widgets react to state changes after notifyListeners.

Common mistakes

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

Practical use

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

Guided practice and next step

FAQ

Is Provider enough for production apps?

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

When should I move to Riverpod or Bloc?

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

Does Provider hurt performance?

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