0
votes

If there are multiple textfields in a screen in flutter which are edited to suitable text and from that screen when the user moves to other screen and comes back to the same screen where the text fields are. How should I make sure that those textfields have the same text which was entered in the fields and not removed in the screen.

TextField(
  decoration: InputDecoration(
    border: InputBorder.none,
    hintText: 'Enter a search term'
  ),
);
3
Please check my answer - Nikunj Kumbhani

3 Answers

2
votes

You should store the input text in a variable so if you return to that screen either it will retain state or you can rebuild but since you have the text stored in a variable you will be able to still show that to user. Use TextEditingController and set its text property accordingly For Example,

TextEditingController _controller = TextEditingController();

Then

_controller.text = <variable>

Take a look at this post

0
votes

Add a TextEditingController to your TextField and call controller.clear() only after pushing the other page.

This can be done either by using await inside the onPressed function or you can use the .then() callback if you want you avoid making your onPressed' function async`.

Example -

//Initialize a controller inside your State class
TextEditingController _controller1 = TextEditingController();
TextEditingController _controller2 = TextEditingController();

//Set the _controller on your both TextFields
TextField(
  controller: _controller1,
  //Rest of your code
)

TextField(
  controller: _controller2,
  //Rest of your code
)

//Values Remain Same after pushing the new page with this
onPressed: () {
   Navigator.push(context, new MaterialPageRoute(
     builder: (context) => NextPage()
   ))
}

//Clear the controller after pushing the new page with this
onPressed: () {
   Navigator.push(context, new MaterialPageRoute(
     builder: (context) => NextPage()
   )).then((value) {
      //This makes sure the textfield is cleared after page is pushed.
      _controller1.clear();
      _controller2.clear();
   });
}
-1
votes
TextEditingController emailController = new TextEditingController();

//Get Value
TextField(
 controller: emailController,
 obscureText: true,
 textAlign: TextAlign.left,
 decoration: InputDecoration(
 border: InputBorder.none,
 hintText: 'PLEASE ENTER YOUR EMAIL',
 hintStyle: TextStyle(color: Colors.grey),
 ),
)
emailController.text