How to get value from TextFormField on Flutter

17,658

Solution 1

You need to use a TextEditingController for example:

TextEditingController lastNameController = TextEditingController();
TextEditingController firstNameController = TextEditingController();
TextEditingController birthdayController = TextEditingController();

Then inside the TextFormField:

child: TextFormField(
  controller: firstNameController,
  decoration: InputDecoration(
  labelText: "Enter First Name",
  enabledBorder: OutlineInputBorder(
  borderRadius: BorderRadius.circular(10.0),
 ),
 // The validator receives the text that the user has entered.
  validator: (value) {
  if (value.isEmpty) {
    return 'Enter last Name';
   }
return null;
   },
),

Create 3 fields, assign each controller to each field. Then to access the value of each controller, you need to use the text property:

 DatabaseReference dbRef = FirebaseDatabase.instance.reference().child("Users");
 dbRef.child("id").set({
        "firstName": firstNameController.text
      })

Check this:

https://flutter.dev/docs/cookbook/forms/retrieve-input

Solution 2

There are 2 ways depending on your use-case:

  1. TextField widget has a callback method onChange which you can use to get value once value is changed.

  2. TextField has a property controller, to which you can asing TextEditingController instance and use it later on where you need it (for example on a button click) like this textFieldController.text which holds the current value of a textField

Share:
17,658
tajihiro
Author by

tajihiro

Updated on June 05, 2022

Comments

  • tajihiro
    tajihiro about 2 years

    I would like to get input value from TextFormField. And then I want to take it into Firebase.

    If I have three TextFormField (last_name / first_name / birthday), how can I get these value and throw them into firebase?

    enter image description here

    • I had already connect and get values from firebase.