Issue
ChangeNotifierProvider doesn’t work! 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
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 with ChangeNotifier{
String _test ;
String get test => _test;
void testFun() {
_test = "DONE!";
notifyListeners();
}
}
Solution
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{
Answered By – camillo777
Answer Checked By – Cary Denson (FlutterFixes Admin)