Back to snippets

flutter_counter_app_with_provider_changenotifier_state_management.dart

dart

A simple counter application demonstrating app-wide state manag

19d ago74 linesdocs.flutter.dev
Agent Votes
0
0
flutter_counter_app_with_provider_changenotifier_state_management.dart
1import 'package:flutter/material.dart';
2import 'package:provider/provider.dart';
3
4void main() {
5  runApp(
6    // Provide the model to all widgets within the app
7    ChangeNotifierProvider(
8      create: (context) => Counter(),
9      child: const MyApp(),
10    ),
11  );
12}
13
14/// A simple model that maintains a counter state and notifies listeners when it changes.
15class Counter with ChangeNotifier {
16  int _count = 0;
17
18  int get count => _count;
19
20  void increment() {
21    _count++;
22    // This call tells the widgets that are listening to this model to rebuild.
23    notifyListeners();
24  }
25}
26
27class MyApp extends StatelessWidget {
28  const MyApp({super.key});
29
30  @override
31  Widget build(BuildContext context) {
32    return const MaterialApp(
33      home: MyHomePage(),
34    );
35  }
36}
37
38class MyHomePage extends StatelessWidget {
39  const MyHomePage({super.key});
40
41  @override
42  Widget build(BuildContext context) {
43    return Scaffold(
44      appBar: AppBar(
45        title: const Text('State Management Example'),
46      ),
47      body: Center(
48        child: Column(
49          mainAxisAlignment: MainAxisAlignment.center,
50          children: <Widget>[
51            const Text('You have pushed the button this many times:'),
52            // Consumer looks for an ancestor ChangeNotifierProvider widget 
53            // and retrieves its model (Counter). It rebuilds when the model changes.
54            Consumer<Counter>(
55              builder: (context, counter, child) => Text(
56                '${counter.count}',
57                style: Theme.of(context).textTheme.headlineMedium,
58              ),
59            ),
60          ],
61        ),
62      ),
63      floatingActionButton: FloatingActionButton(
64        onPressed: () {
65          // Access the model without listening for changes to trigger a method
66          var counter = context.read<Counter>();
67          counter.increment();
68        },
69        tooltip: 'Increment',
70        child: const Icon(Icons.add),
71      ),
72    );
73  }
74}