I'm using multiProvider to manage state in flutter. The main problem that i'm facing is; Unable to clear the data inside my viewModel after closing a page. When i open the page again, old data is populating from viewModel.
Because of this issue i've created a 'reset' method in my viewModel & calling this 'reset' method before open the page.
Is there any way to remove old values from viewModel:- Please suggest
My code:
Main Page Adding providers under multi provider
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: ViewModel1()),
ChangeNotifierProvider.value(value: ViewModel2()),
],
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
),
//Set Home Page after splash
home: HomePage(),
));
);
}
}
This is my Homepage Navigate to FirstPage & reset ViewModel1 data
HomePage()
{
:
:
:
onPressed(){
Navigator.push(
context, MaterialPageRoute(builder: (context) => FirstPage()));
Provider.of<ViewModel1>(context, listen: false).reset();
}
}
This is My Page
class FirstPage extends StatefulWidget {
@override
_FirstPageState createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
@override
Widget build(BuildContext context) {
final ViewModel1 _viewModel1 =
Provider.of<ViewModel1>(context, listen: true);
TextFormField(
controller: _fNameController,
onChanged: _viewModel1.setFname,
)
}
}
This is my ViewModel
class ViewModel1 with ChangeNotifier {
String _fName = '';
String get fName => _fName;
setFname(String fName) {
_fName = fName;
notifyListeners();
setFnameValidation(fName.trim().isNotEmpty ? true : false);
}
//TODO Reset all values
void reset()
{
_fName = '';
notifyListeners();
}
}
If you are reusing one model on different pages, without sharing data between pages.. It's better to create and close the model on every page.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.