简体   繁体   中英

Validator message moves the placeholder of TextFormField

I am creating a login page using flutter. If there is no validator error, my input fields look like this: InputImage

But if the validator returns a message the message moves the icon and placeholder of my input field like this:

InputImage2

How can I fix it?

My code for input widgets is below:

class InputFieldWidget extends StatelessWidget {
  final TextEditingController cnt;
  final String placeholder;
  final Widget? icon;
  final GlobalKey formKey;

  const InputFieldWidget(
      {required this.cnt, required this.placeholder, required this.icon, required this.formKey} );

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Palette.lightGrey,
      ),
      height: 50,
      margin: EdgeInsets.all(10),
      child: Form(
        key: formKey,
        child: TextFormField(
          validator: (value){
            if(value == null || value.isEmpty) {
              return "      $placeholder is not valid!";
            }
          },
          cursorColor: Palette.lightPurple,
          controller: cnt,
          decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: const EdgeInsets.symmetric(vertical: 15),
              prefixIcon: icon,
              hintText: placeholder,
              focusColor: Palette.lightPurple),
        ),
      ),
    );
  }
}

I customised you code:

You don't need to take Container for your Ui. TextFormField give us properties to achieve like your Ui:}

Below the example code it's help you:

import 'package:flutter/material.dart';

class InputFieldWidget extends StatelessWidget {
final TextEditingController cnt;
final String placeholder;
final Widget? icon;
final GlobalKey? formKey;

 InputFieldWidget(
  {required this.cnt,
  required this.placeholder,
  required this.icon,
  this.formKey});

  @override
  Widget build(BuildContext context) {
  return Form(
  key: formKey,
  child: TextFormField(
    validator: (value) {
      if (value == null || value.isEmpty) {
        return "      $placeholder is not valid!";
      }
    },
    cursorColor: Colors.grey,
    controller: cnt,
    decoration: InputDecoration(
        border: InputBorder.none,
        fillColor: Palette.lightGrey, 
        filled: true,
        contentPadding: const EdgeInsets.symmetric(vertical: 15),
        prefixIcon: icon,
        hintText: placeholder,
        focusColor: Colors.grey),
  ),
);
  }
   }

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