Flutter Textformfield should be responsive to typing and error

Issue

I’ve often seen where fields are responsive when users are typing, giving realtime feedback. An example is when I’m typing confirm password or email, if the confirm password or email hasn’t matched the password while typing it returns error by marking turning the border of the field red until it matches the correct input. I have written this code, how do I improve the code to be responsive as described.

  Widget _buildConfirmPasswordTF() {
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
      // Text('Password', style: kLabelStyle,),
      SizedBox(height: 10.0),
      Container(alignment: Alignment.centerLeft, decoration: kBoxDecorationStyle, height: 60.0, child: TextFormField(
        validator: ( confirmPassword ){
          if ( confirmPassword.trim() != _password.isValidPassword ) {
            return null;
          }  else {
            return 'Password doesn\'t match';
            }
        },
        obscureText: true, style: TextStyle(color: Colors.white, fontFamily: 'OpenSans',),
        decoration: InputDecoration(border: InputBorder.none, contentPadding: EdgeInsets.only(top: 14.0),
          prefixIcon: Icon(Icons.lock, color: Colors.white,),
          hintText: 'Enter Confirm Password',
          hintStyle: kHintTextStyle,
          errorBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.red ) ),
          focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.red ) )
        ),
      ),
      ),
    ],
    );
  }

This is where I set the hintText

final kHintTextStyle = TextStyle(
  color: Colors.white54,
  fontFamily: 'OpenSans',
);

This is where I set the labelStyle

final kLabelStyle = TextStyle(
  color: Colors.white,
  fontWeight: FontWeight.bold,
  fontFamily: 'OpenSans',
);

This is where I set the border decoration

final kBoxDecorationStyle = BoxDecoration(
  color: Color(0xFF6CA8F1),
  borderRadius: BorderRadius.circular(10.0),
  boxShadow: [
    BoxShadow(
      color: Colors.black12,
      blurRadius: 6.0,
      offset: Offset(0, 2),
    ),
  ],
);

Solution

you need autovalidateMode: AutovalidateMode.onUserInteraction, pass this in textformfield.

Answered By – Piyush Kumar

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.