I want the TextFormFied value to persist even when navigating to another page and coming back.
I think it can be achieved by using Provider. but don’t know how to update the controller with the proivder class instance variable.
Here is the code I tried.
TextFormField on UI
TextFormField(
amountController: amountController,
onChanged: (value){
provider.amount(value);
},
)),
Provider methode to get user entered value.
String? value ;
amount(String newAmount) {
value = newAmount;
notifyListeners();
}
I don’t know whether it’s correct or not.
Let me know how to update the amountController
by value
.
If this approach is wrong, Please let me know. What are the possible ways to achieve it?
2
Answers
As you have attached very less code, let’s see you have done these below things right:
Created a Model class:
model class that holds the state you want to persist. This will be the class you provide using
ChangeNotifierProvider
, with having a function which will save the value and notify the listeners.Wrapped your widget tree with Provider, simple thing.
Saving the value and using it with the help of Provider:
If you have a stateful widget here, you could set text of your controller inside
initState
function like this:so when you get to this page, text field is initialized with the value from provider.