1// Copyright 2014 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5import 'package:flutter/material.dart';
6
7/// Flutter code sample for a [ChangeNotifier] with a [ListenableBuilder].
8
9void main() {
10 runApp(const ListenableBuilderExample());
11}
12
13class CounterModel with ChangeNotifier {
14 int _count = 0;
15 int get count => _count;
16
17 void increment() {
18 _count += 1;
19 notifyListeners();
20 }
21}
22
23class ListenableBuilderExample extends StatefulWidget {
24 const ListenableBuilderExample({super.key});
25
26 @override
27 State<ListenableBuilderExample> createState() => _ListenableBuilderExampleState();
28}
29
30class _ListenableBuilderExampleState extends State<ListenableBuilderExample> {
31 final CounterModel _counter = CounterModel();
32
33 @override
34 Widget build(BuildContext context) {
35 return MaterialApp(
36 home: Scaffold(
37 appBar: AppBar(title: const Text('ListenableBuilder Example')),
38 body: CounterBody(counterNotifier: _counter),
39 floatingActionButton: FloatingActionButton(
40 onPressed: _counter.increment,
41 child: const Icon(Icons.add),
42 ),
43 ),
44 );
45 }
46}
47
48class CounterBody extends StatelessWidget {
49 const CounterBody({super.key, required this.counterNotifier});
50
51 final CounterModel counterNotifier;
52
53 @override
54 Widget build(BuildContext context) {
55 return Center(
56 child: Column(
57 mainAxisAlignment: MainAxisAlignment.center,
58 children: <Widget>[
59 const Text('Current counter value:'),
60 // Thanks to the ListenableBuilder, only the widget displaying the
61 // current count is rebuilt when counterValueNotifier notifies its
62 // listeners. The Text widget above and CounterBody itself aren't
63 // rebuilt.
64 ListenableBuilder(
65 listenable: counterNotifier,
66 builder: (BuildContext context, Widget? child) {
67 return Text('${counterNotifier.count}');
68 },
69 ),
70 ],
71 ),
72 );
73 }
74}
75

Provided by KDAB

Privacy Policy
Learn more about Flutter for embedded and desktop on industrialflutter.com