Show Flutter TextFormField error on top of input

49 views Asked by At

I'd like to show the flutter TextFormField error on top of the input - not below. Can i achieve this with TextFormField itself or do I have to build it myself?

Thank you in advance.

A flutter textformfield with the error on top of the input

1

There are 1 answers

0
Hamou Ouyaba On BEST ANSWER

check this code :

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Custom TextFormField Error'),
        ),
        body: const MyForm(),
      ),
    );
  }
}

class MyForm extends StatefulWidget {
  const MyForm({Key? key}) : super(key: key);

  @override
  MyFormState createState() => MyFormState();
}

class MyFormState extends State<MyForm> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  String inputValue = '';
  String? errorText;

  void validateInput(String value) {
    setState(() {
      errorText = value.isEmpty ? 'This field is required' : null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Form(
        key: formKey,
        child: Column(
          children: <Widget>[
            if (errorText != null)
              Text(
                errorText!,
                style: const TextStyle(color: Colors.red),
              ),
            TextFormField(
              decoration: const InputDecoration(labelText: 'Input Field'),
              onChanged: (value) {
                validateInput(value);
                setState(() {
                  inputValue = value;
                });
              },
            ),
            ElevatedButton(
              onPressed: () {
                formKey.currentState!.validate();
                setState(() {
                  errorText =
                      inputValue.isEmpty ? 'This field is required' : null;
                });

                if (formKey.currentState!.validate()) {
                  // Do something with the valid input
                }
              },
              child: const Text('Submit'),
            ),
          ],
        ),
      ),
    );
  }
}