Use ListenableBuilder
.
This is a supplemental answer demonstrating using a ListenableBuilder
to rebuild the UI on a change from a ChangeNotifier
.
It's just the standard counter app.
counter_model.dart
import 'package:flutter/foundation.dart';
class CounterModel extends ChangeNotifier {
int _counter = 0;
int get count => _counter;
void increment() {
_counter++;
notifyListeners();
}
}
main.dart
import 'counter_model.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _counterModel = CounterModel();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
ListenableBuilder(
listenable: _counterModel,
builder: (context, child) {
return Text(
'${_counterModel.count}',
style: Theme.of(context).textTheme.headlineMedium,
);
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _counterModel.increment,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
Update: Previously this answer demonstrated the use of AnimatedBuilder
.
Note: In this particular case (as in most cases), a ValueNotifier
and ValueListenableBuilder
would be sufficient. See Flutter state management for minimalists.