A simple provider example
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(ChangeNotifierProvider(
create: (_) => Foo(),
child: MyApp(),
));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Find the Provider above and get value from Foo object
var value = Provider.of<Foo>(context).value;
print(value);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Column(
children: [
Center(child: Text(value)),
Center(
child: RaisedButton(
onPressed: () {
//Call the method _goodBye from Foo using provider
Provider.of<Foo>(context, listen: false)._goodBye();
print(value);
},
child: Text('Click', style: TextStyle(fontSize: 20)),
)
),
Center(
child: RaisedButton(
onPressed: () {
//Call the method _goodBye from Foo using provider
Provider.of<Foo>(context, listen: false)._reset();
print(value);
},
child: Text('Reset', style: TextStyle(fontSize: 20)),
)
),
],
)),
);
}
}
class Foo extends ChangeNotifier {
//Initial private state of the value
var _value = "Hello";
//Getter
String get value {
return _value;
}
//Method to Update Value
_goodBye() {
_value = "Goodbye";
notifyListeners();
}
//Method to Reset
_reset() {
_value = "Rest";
notifyListeners();
}
}
Using the Consumer class.
You can rework the code above to use a Consumer.
According to the documentation:
"The Consumer widget doesn't do any fancy work. It just calls Provider.of in a new widget, and delegates its build
implementation to builder."
If you compare the code above to this example, you will see I was able to remove var value = Provider.of<Foo>(context).value;
and let Consumer handle this work.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(ChangeNotifierProvider(
create: (_) => Foo(),
child: MyApp(),
));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
//This is no longer needed with Consumer
//var value = Provider.of<Foo>(context).value;
//print(value);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Column(
children: [
Consumer<Foo>(
builder: (_, foo, child) => Text(foo.value)
),
Center(
child: RaisedButton(
onPressed: () {
//Call the method _goodBye from Foo using provider
Provider.of<Foo>(context, listen: false)._goodBye();
},
child: Text('Click', style: TextStyle(fontSize: 20)),
)
),
Center(
child: RaisedButton(
onPressed: () {
//Call the method _goodBye from Foo using provider
Provider.of<Foo>(context, listen: false)._reset();
//print(value);
},
child: Text('Reset', style: TextStyle(fontSize: 20)),
)
),
],
)),
);
}
}
- Log in to post comments