[英]Flutter - MultiProvider (ChangeNotifierProvider) doesn't work
ChangeNotifierProvider doesn't work. ChangeNotifierProvider 不起作用。 I don't know what is the problem?
我不知道是什么问题? Could anyone tell me what's wrong with this code?
谁能告诉我这段代码有什么问题? Thank you
谢谢
I want to pass the test value to the next page.我想将测试值传递到下一页。
Here is the main function and the providers这是主要的 function 和供应商
void main() {
runApp(
MultiProvider(
providers:[
ChangeNotifierProvider<ProductsNotifier>(create:(context)=> ProductsNotifier()),
// second provider...
],
child:MaterialApp( home: MyApp())
)
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Provider
return Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: Container(
child:RaisedButton(
onPressed: (){
ProductsNotifier obj = new ProductsNotifier();
obj.testFun();
Navigator.push(context,
MaterialPageRoute(builder: (context) => NextPage()),
);
},
child: Text('GO TO THE NEXT PAGE'),
)
),
);
}
}
Next Page:下一页:
class NextPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
var txt = Provider.of<ProductsNotifier>(context);
return Scaffold(
appBar: AppBar(
title: Text('Next Page'),
),
body: Container(
child: Text(txt.test.toString()),
),
);
}
}
Class ProductsNotifier Class ProductsNotifier
class ProductsNotifier with ChangeNotifier{
String _test ;
String get test => _test;
void testFun() {
_test = "DONE!";
notifyListeners();
}
}
First remove this line:首先删除这一行:
ProductsNotifier obj = new ProductsNotifier();
It is already created here:它已经在这里创建:
ChangeNotifierProvider<ProductsNotifier>(create:(context)=> ProductsNotifier()),
Then然后
class ProductsNotifier with ChangeNotifier{
replace with:用。。。来代替:
class ProductsNotifier extends ChangeNotifier{
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.