This is a supplemental answer demonstrating using an AnimatedBuilder
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(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState 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>[
Text(
'You have pushed the button this many times:',
),
AnimatedBuilder(
animation: _counterModel,
builder: (context, child) {
return Text(
'${_counterModel.count}',
style: Theme.of(context).textTheme.headline4,
);
}
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _counterModel.increment,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
AnimatedBuilder
(orAnimatedWidget
if you want some custom class that extendsAnimatedWidget
)ChangeNotifier
, and within it lies multiple simple/complexValueNotifiers
. UI is notified accordingly via the whole ViewModelnotifyListeners()
or its fine-tuned property ValueNotifiers. I useChangeNotifier
for the ViewModel, because aValueNotifier
subclass requires equality check==
for notification. Which means overriding said==
+hashCode
or usingEquatable
.ChangeNotifier
builder. And this question/answer fit perfectly for this particular scenario.ChangeNotifier
for its simplicity and ease of use. I've never had to override==
andhashCode
in my value notifier, though.