I have a lot of data objects. Each with a ChangeNotifier
. So I want to update the smallest area possible. What must be changed to make this example work?
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
MyData _myData;
@override
void initState() {
_myData = MyData(title: 'Really my data');
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Provider Test'),
),
body: Center(
child: ChangeNotifierProvider<MyData>.value(
value: _myData,
builder: (BuildContext _, Widget __) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(_myData.toString()),
RaisedButton(
child: Text('edit'),
onPressed: () => _myData.incrementCounter(),
),],);},),),);}}
class MyData with ChangeNotifier {
String title;
int counter = 0;
MyData({
this.title,
});
void incrementCounter() {
counter++;
print('counter=$counter');
notifyListeners();
}
void setTitle(String newValue) {
title = newValue;
notifyListeners();
}
String toString() => '$title - $counter';
}
question from:https://stackoverflow.com/questions/65830117/why-is-changenotifierprovider-value-not-updating-its-builder