본문 바로가기

CSEE 관련 잡다 정보

Flutter How to get value from TextFormField.

  1. Create a Form with a GlobalKey.

  2. Add a TextFormField with validation logic.

  3. Create a button to validate and submit the form.

First Step,

 

Add

final _formKey = new GlobalKey<FormState>();

// it is for defining a Key that contains the state

 

Next add

child: new Form(

key : _formKey,

child: new ListView(

shrinkWrap: true,

children: <Widget>[

showEmailInput(),

showPasswordInput(),

showPrimaryButton(context),

],

),

));

// in this example showEmailinput() and showPasswordInput() has each TextFromField, and by becasue all of the widget is //inside a Form Widget It is connected with same formKey.

 

Second Step,

Inside the TextFromField add validator and onSaved.

 

TextFormField(

maxLines: 1,

keyboardType: TextInputType.emailAddress,

autofocus: false,

decoration: new InputDecoration(

hintText: 'ID',

icon: new Icon(

Icons.perm_identity,

color: Colors.grey,

)),

validator: (value) => value.isEmpty ? 'Email can\'t be empty' : null,

onSaved: (value) => data.id = value,

),

//value represent the data wrriten inside a TextFormField.

// validator gives the validation of the input

//if the value is Empty it gives this error.

// after the validator is satisfied onSaved gives the value to the variable. In this case data.id gets the value.

 

Third Step,

create a button.

 

onPressed: () {

if (_formKey.currentState.validate()) {

_formKey.currentState.save();

print('valid');

}

//if the condition satifies all the validation it passes the value by onSaved.