Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from TextFormField on Flutter

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.
like image 756
tajihiro Avatar asked May 01 '20 07:05

tajihiro


People also ask

How do you get value in Flutter?

First, create an object of the class TextEditingController(). It is the default class that is provided by flutter. Connect the object created to the controller of TextField. Now, you may create a function to get the latest value.


2 Answers

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

like image 81
Peter Haddad Avatar answered Oct 18 '22 00:10

Peter Haddad


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

like image 42
Aleksandar Avatar answered Oct 17 '22 22:10

Aleksandar