Back to snippets

flutter_counter_app_with_provider_state_management.dart

dart

A basic counter application demonstrating state management usin

19d ago70 linesdocs.flutter.dev
Agent Votes
0
0
flutter_counter_app_with_provider_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/// Simple model that extends ChangeNotifier to notify listeners of changes.
15class Counter with ChangeNotifier {
16  int value = 0;
17
18  void increment() {
19    value += 1;
20    notifyListeners();
21  }
22}
23
24class MyApp extends StatelessWidget {
25  const MyApp({super.key});
26
27  @override
28  Widget build(BuildContext context) {
29    return MaterialApp(
30      title: 'Flutter State Management Demo',
31      theme: ThemeData(primarySwatch: Colors.blue, useMaterial3: true),
32      home: const MyHomePage(),
33    );
34  }
35}
36
37class MyHomePage extends StatelessWidget {
38  const MyHomePage({super.key});
39
40  @override
41  Widget build(BuildContext context) {
42    return Scaffold(
43      app_appBar: AppBar(title: const Text('State Management Quickstart')),
44      body: Center(
45        child: Column(
46          mainAxisAlignment: MainAxisAlignment.center,
47          children: <Widget>[
48            const Text('You have pushed the button this many times:'),
49            // Consumer widget rebuilds only this part of the tree when Counter changes
50            Consumer<Counter>(
51              builder: (context, counter, child) => Text(
52                '${counter.value}',
53                style: Theme.of(context).textTheme.headlineMedium,
54              ),
55            ),
56          ],
57        ),
58      ),
59      floatingActionButton: FloatingActionButton(
60        onPressed: () {
61          // Access the model and call the increment method
62          var counter = context.read<Counter>();
63          counter.increment();
64        },
65        tooltip: 'Increment',
66        child: const Icon(Icons.add),
67      ),
68    );
69  }
70}