Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/Dart - How to Save State when Navigating back to a Form with Textfields?

Currently, when a user fills in a TextField the text is lost if they navigate away and then return. How can I get the text to stay in the field upon their return?

Here's the stateful widget I'm using;

  class _EditPageState extends State<EditPage> {

  final _formKey = GlobalKey<FormState>();
  String audiotitle;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Container(
          child: TextField(      
            decoration: new InputDecoration(
              hintText: widget.oldaudiotitle,           
            ),
            keyboardType: TextInputType.text,
            onChanged: (titleText) {
              setState(() {
                this.audiotitle = titleText;
              });
            },
          ),
        ),
      ),
    );
  }
}

What am I doing wrong here?

like image 961
Meggy Avatar asked Oct 25 '25 05:10

Meggy


1 Answers

you have two ways :

  1. store the Data of the text field and set the data in init method (use sharedpreferences or any other database as per your requirements)
TextEditingController controller = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    // retrive the Data
    if(data != null) {
      controller = new TextEditingController(text: data);
    }
  }

or if the first screen is navigating in the second Screen than just pop that screen

      Navigator.pop(context);
like image 128
Yash Aervadiya Avatar answered Oct 26 '25 21:10

Yash Aervadiya