简体   繁体   中英

How to show label and error message inside the boundry of textformfield in flutter?

I'm using a text and textformfield inside a container to get userName. I need to do the text field validation and get the error message and red color boundary box as shown in expected outcome image. I have included the current output also. I tried a few other ways also. But nothing worked.

Current output

Expected Output

    decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(10)),
        shape: BoxShape.rectangle,
        color: Color(0xFFF4F9FE),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.fromLTRB(10, 3, 0, 0),
            child: Text("Full Name",
              style: TextStyle(color: Color(0xFFA8C3EC)),
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
            child: TextFormField(
              decoration: new InputDecoration(
                hintText: "Enter Your Full Name",
                border: InputBorder.none,
                focusedBorder: InputBorder.none,
                enabledBorder: InputBorder.none,
                errorBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10.0),
                  borderSide: BorderSide(color:  Colors.red),
                ),
                disabledBorder: InputBorder.none,
                contentPadding: const EdgeInsets.symmetric(vertical: 1.0),
              ),
              validator: _validateName,
            ),
          ),
        ],
      ),
    );

String _validateName(String value) {
    return "Required field cannot be empty";
}

Flutter TextFormField handles error text itself, so we don't require to use variable _validate. It will check at runtime whether you satisfied the condition or not.

final confirmPassword = TextFormField(
  controller: widget.confirmPasswordController,
  obscureText: true,
  decoration: InputDecoration(
    prefixIcon: Icon(Icons.lock_open, color: Colors.grey),
    hintText: 'Confirm Password',
    errorText: validatePassword(widget.confirmPasswordController.text),
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
  ),
);

String validatePassword(String value) {
  if (!(value.length > 5) && value.isNotEmpty) {
    return "Password should contain more than 5 characters";
  }
  return null;
}

Note: User must add at least one character to get this error message. More info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM