как добавить чекер и предупреждение в TextField

Вот код, который я хочу добавить предупреждение об ошибке и соответствующую проверку.

TextField(
  controller: emailController,
  decoration: InputDecoration(
    hintText: '[email protected]',
    labelText: 'Email',
    // icon: Icon(Icons.mail),
    suffixIcon: emailController.text.isEmpty
        ? Container(width: 0)
        : IconButton(
            icon: Icon(Icons.close),
            onPressed: () => emailController.clear(),
          ),
    border: OutlineInputBorder(),
    focusColor: Colors.red
  ),
  keyboardType: TextInputType.emailAddress,
  textInputAction: TextInputAction.done,
  // autofocus: true,
),

Как сделать так, чтобы появилось предупреждение об ошибке, если человек не вставил @ gmail.com Сообщение об ошибке выглядит


person Macchiato    schedule 23.05.2021    source источник


Ответы (1)


Вы можете использовать виджет Form() с TextFormField() и внутри TextFormField()

добавьте validator(val){ // you qualify checker } и тогда вы можете позвонить

_key.currentState.validate() по нажатию кнопки, чтобы подтвердить свой адрес электронной почты.

class _MyWidgetState extends State<MyWidget> {
final GlobalKey<FormState> _key = GlobalKey(); 

var emailController = TextEditingController();

@override
Widget build(BuildContext context) {
return Container(
        height:150,
        child: Column(
          children:[
            Form(
                key: _key,
                child:TextFormField(
                  controller: emailController,
                  decoration: InputDecoration(
                      hintText: '[email protected]',
                      labelText: 'Email',
                      // icon: Icon(Icons.mail),
                      suffixIcon: emailController.text.isEmpty
                          ? Container(width: 0)
                          : IconButton(
                        icon: Icon(Icons.close),
                        onPressed: () => emailController.clear(),
                      ),
                      border: OutlineInputBorder(),
                      focusColor: Colors.red
                  ),
                  keyboardType: TextInputType.emailAddress,
                  textInputAction: TextInputAction.done,
                  // autofocus: true,
                  onFieldSubmitted: (val){
                    _key.currentState!.validate();
                  },
                  validator: (val){
                    if(!val!.contains("@")){
                      return "invalid email";
                    }
                    return null;
                  },
                )
            ),
            ElevatedButton(onPressed: () {
              _key.currentState.validate();
            }, child: Text("Check"),)
          ],
        ),
      );
     }
    }
person Chirag Bargoojar    schedule 23.05.2021
comment
откуда взялся _key? - person Macchiato; 23.05.2021
comment
Его глобальный ключ для контрольной строки формы №. 2 в коде - person Chirag Bargoojar; 23.05.2021
comment
«Это требует, чтобы была включена языковая функция, не допускающая значения NULL» Я получил эту ошибку - person Macchiato; 23.05.2021
comment
if(!val!.contains("@")) удалите ! после val и из _key.currentState!.validate();, что исправит это. - person Chirag Bargoojar; 23.05.2021