Reading a value
The easiest way to read a value is by using the extension methods on [BuildContext]:
context.watch<T>()
, which makes the widget listen to changes onT
context.read<T>()
, which returnsT
without listening to itcontext.select<T, R>(R cb(T value))
, which allows a widget to listen to only a small part ofT
.
One can also use the static method Provider.of<T>(context)
, which will behave similarly to watch
. When the listen
parameter is set to false
(as in Provider.of<T>(context, listen: false)
), then it will behave similarly to read
.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
//Step 1: create the model=======================
class PizzaProvider extends ChangeNotifier {
late int numPizza;
PizzaProvider({
this.numPizza = 0
});
void set_numPizza(int new_value){
numPizza = new_value;
notifyListeners();
}
}
//Step 1 end=====================================
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
//Step 2: Setup/Activate the provider================
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context)=>PizzaProvider())
],
child: MaterialApp(
//Step 2 end=====================================
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
//Step 3: get value of Provider when build==========================
int numPizza = Provider.of<PizzaProvider>(context).numPizza;
//==================================================================
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Pizza:'+numPizza.toString(),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
//Step 4: set the value==========================================================
Provider.of<PizzaProvider>(context,listen: false).set_numPizza(numPizza+1);
//===============================================================================
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
沒有留言:
發佈留言