0
0
Fluttermobile~20 mins

ChangeNotifier and Consumer in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Counter with ChangeNotifier
A simple counter app that uses ChangeNotifier to manage state and Consumer to update the UI when the count changes.
Target UI
---------------------
| Counter with State |
---------------------
|                   |
|      Count: 0     |
|                   |
|   [Increment +]   |
|                   |
---------------------
Use ChangeNotifier to hold an integer count value.
Create a ChangeNotifierProvider to provide the counter to the widget tree.
Use Consumer widget to listen to changes and update the displayed count.
Add a button labeled 'Increment +' that increases the count by 1 when tapped.
Starter Code
Flutter
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => Counter(),
      child: const MaterialApp(
        home: CounterScreen(),
      ),
    );
  }
}

class Counter extends ChangeNotifier {
  int _count = 0;

  int get count => _count;

  void increment() {
    // TODO: Increase _count by 1 and notify listeners
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Counter with State')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('Count:'),
            // TODO: Use Consumer to show current count
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // TODO: Call increment on Counter
              },
              child: const Text('Increment +'),
            ),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => Counter(),
      child: const MaterialApp(
        home: CounterScreen(),
      ),
    );
  }
}

class Counter extends ChangeNotifier {
  int _count = 0;

  int get count => _count;

  void increment() {
    _count++;
    notifyListeners();
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Counter with State')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('Count:'),
            Consumer<Counter>(
              builder: (context, counter, child) {
                return Text(
                  '${counter.count}',
                  style: const TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
                );
              },
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                context.read<Counter>().increment();
              },
              child: const Text('Increment +'),
            ),
          ],
        ),
      ),
    );
  }
}

We created a Counter class that extends ChangeNotifier. It holds a private integer _count and a getter count. The increment() method increases _count by 1 and calls notifyListeners() to tell widgets to update.

In MyApp, we use ChangeNotifierProvider to provide the Counter instance to the widget tree.

In CounterScreen, we use a Consumer<Counter> widget to listen for changes and rebuild the Text widget showing the current count.

The button calls context.read<Counter>().increment() to update the count.

This setup keeps state management clean and UI reactive without manual setState calls.

Final Result
Completed Screen
---------------------
| Counter with State |
---------------------
|                   |
|      Count: 0     |
|                   |
|   [Increment +]   |
|                   |
---------------------
Tapping 'Increment +' increases the number shown after 'Count:' by 1.
The count updates immediately on screen without page reload.
Stretch Goal
Add a 'Reset' button that sets the count back to zero.
💡 Hint
Add a reset() method in Counter that sets _count to 0 and calls notifyListeners(). Add another ElevatedButton that calls context.read<Counter>().reset() on press.