Daniel
Daniel

Reputation: 111

Flutter: Save TextField value

I am new to flutter. I want to implement a simple Form function:

1) First page: "This is the name:" $stringname

1.1) Click on 'Edit icon' --> Open Second Page

2) Second Page: "Edit name:" TextField

2.1) Use Back-Button --> Go back to First Page --> Displays new $stringname

[3) Visit Second Page again, Textfield shows last saved name]

I implemented everything(Frist Page with edit icon, second page with back button and text field), but I don't know how to save the new string value and send it to the first page. Could someone please give me a short example how to do this?

TextField(
  obscureText: false,
  decoration: InputDecoration(
    border: OutlineInputBorder(
      borderRadius: BorderRadius.all(
        const Radius.circular(12.0),
      ),
    ),
    labelText: 'Name',
    labelStyle: TextStyle(
      color: Colors.black.withOpacity(0.8)
    ),    
  ),
),

Upvotes: 1

Views: 13722

Answers (1)

J. S.
J. S.

Reputation: 9635

To get the data back from the second page to the first page you need to be expecting to receive the data from the second page when you Navigate to it. On the second page you need to take the value from the TextField and send it back when you pop the view back to the first page, like this:

In the first page

Method

void goToSecondPage(){
  Navigator.of(context).push(MaterialPageRoute(
    builder: (context){
      return SecondPage();
    }
  )).then((valueFromTextField){
    // use your valueFromTextField from the second page
  });
}

Second page

Declaration

TextEditingController _textEditingController = TextEditingController();

Widget

Column(
  children: <Widget>[
    TextField(
      controller: _textEditingController,
      obscureText: false,
      decoration: InputDecoration(
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(
            const Radius.circular(12.0),
          ),
        ),
        labelText: 'Name',
        labelStyle: TextStyle(
          color: Colors.black.withOpacity(0.8)
        ),
      ),
    ),
    RaisedButton(
      onPressed: () => submit(),
    ),
  ],
),

Method

void submit(){
  Navigator.of(context).pop(_textEditingController.text);
}

Upvotes: 2

Related Questions