Skip to content

Instantly share code, notes, and snippets.

@evaisse
Last active June 30, 2025 13:19
Show Gist options
  • Save evaisse/4f4d236ae76d03017ddf4e7f1bc8a296 to your computer and use it in GitHub Desktop.
Save evaisse/4f4d236ae76d03017ddf4e7f1bc8a296 to your computer and use it in GitHub Desktop.
ChangeNotifier with provider
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
/// Data model for the counter, extending ChangeNotifier to notify listeners of changes.
class CounterData extends ValueNotifier<int> {
CounterData() : super(0);
void increment() => value = value + 1;
}
/// A widget that displays the current count,
/// retrieved from the provided [CounterData] using Provider.
class CountDisplayWidget extends StatelessWidget {
final int? counter;
/// Creates a [CountDisplayWidget].
const CountDisplayWidget({super.key, required this.counter});
@override
Widget build(context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Current Count:', style: TextStyle(fontSize: 20)),
Text(
counter?.toString() ?? '-',
style: Theme.of(context).textTheme.headlineMedium,
),
],
);
}
}
/// The main application widget that builds the UI,
/// interacting with the counter state via Provider.
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
/// on recup la méthode increment du compteur
final counterData = context.watch<CounterData?>();
return Scaffold(
appBar: AppBar(
title: const Text('Counter Application'),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
),
body: Center(child: CountDisplayWidget(counter: counterData?.value)),
floatingActionButton: FloatingActionButton(
onPressed: counterData?.increment,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter Application',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
// Provide the CounterData ChangeNotifier to the widget tree.
home: ChangeNotifierProvider(
create: (context) => CounterData(),
builder: (context, child) => const HomePage(),
),
);
}
}
void main() {
runApp(const MyApp());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment