With ChangeNotifierProvider<MyData>.value
you provided MyData to the Widgets below it, but you don't use it anywhere. To watch changes in MyData use for example a Consumer
widget.
Here's the fixed code using consumer:
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>[
Consumer<MyData>(
builder: (context, mydata, child) {
return 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';
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…