FlutterIntermediate 2 min read

Share a small model with ChangeNotifier

Separate a small model from the interface using ChangeNotifier and rebuild only the dependent area.

On this page

A shared model should describe the data and the operations that change it. The interface listens for changes and renders a view of that model.

Move behavior into a model

main.dart
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: FocusPage()));

class FocusModel extends ChangeNotifier {
  int _sessions = 0;
  int get sessions => _sessions;
  void finishSession() { _sessions++; notifyListeners(); }
}

class FocusPage extends StatefulWidget {
  const FocusPage({super.key});
  @override
  State<FocusPage> createState() => _FocusPageState();
}
class _FocusPageState extends State<FocusPage> {
  final model = FocusModel();
  @override
  void dispose() { model.dispose(); super.dispose(); }
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Focus sessions')),
    body: Center(child: ListenableBuilder(listenable: model,
      builder: (context, child) => Text('${model.sessions} completed'))),
    floatingActionButton: FloatingActionButton(
      onPressed: model.finishSession, child: const Icon(Icons.check)),
  );
}

Ownership still matters

The page creates this model, so the page disposes it. If a parent or dependency container creates a longer-lived model, that owner should control its lifecycle instead.

ListenableBuilder reacts to the notification. The model does not need to know what widgets are on screen.

Scale from a clear boundary

Provider, Riverpod and Bloc offer different ways to expose and coordinate state. Learn the ownership and data-flow problem before choosing an abstraction. A package cannot decide which part of your application should own a value.

Trace the notification without mixing model and interface

The button calls a model operation. That operation changes the stored count and notifies listeners. ListenableBuilder reacts by running its builder with the current model value. The model never needs to locate a Text widget or know where the number is painted.

The page creates the model once and disposes it at the end of its lifetime. Recreating the model in build would reset its data and make subscriptions difficult to reason about.

When another feature needs the same model, decide whether the owner should move above both features. Provider can expose such a scope, but the package does not remove the need to decide the scope correctly.

Try it yourself

Add resetSessions to the model. Call it from a second control, and verify both controls update the same display without storing a second count.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.