Derence
Derence

Reputation: 428

How can I center the error text of a TextFormField in Flutter?

I have a TextFormField that displays an error message when invalid. It works great, but I'd like the error text to be centered.

FormTextField with error message displayed

Container(
    child: TextFormField(
    validator: (val) => val.isEmpty ? 'Enter a Username' : null,
    onChanged: (val) {setState(() => username = val);},
    textAlign: TextAlign.center,
    decoration: InputDecoration(
        hintText: 'Pick Your Username',
        errorStyle: // is it possible to center the errorText?
        ),
    ),
),

Using the errorStyle property, I can change the color, weight, size, etc. However, I haven't been able to figure out how to get the little red text that appears when the TextFormField is invalid to center.

Thanks in advance for any advice!

Upvotes: 2

Views: 3142

Answers (1)

Omatt
Omatt

Reputation: 10453

The default style of the error for Material TextField is displayed on the lower left portion of the Widget. If you'd like to modify how the error is displayed, you can create a Widget to display the error message.

Here's a sample.

import 'package:flutter/material.dart';

class SampleTextField extends StatefulWidget {
  const SampleTextField({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<SampleTextField> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<SampleTextField> {
  final _formKey = GlobalKey<FormState>();
  bool textFieldError = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: StatefulBuilder(
        builder:
            (BuildContext context, void Function(void Function()) setState) {
          return Center(
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    onFieldSubmitted: (String text) {
                      _formKey.currentState!.validate();
                    },
                    validator: (String? text) {
                      // Update textFieldError to determine if an error should be displayed
                      setState(() {
                        textFieldError = text == null || text.isEmpty;
                        debugPrint('Error: $textFieldError');
                      });
                      // Return a null on validator to not display the default error from the TextField
                      return null;
                    },
                    decoration: const InputDecoration(
                      hintText: 'Hint Text',
                      border: OutlineInputBorder(),
                    ),
                  ),
                  textFieldError
                      ? const Text('Error Text',
                          style: TextStyle(color: Colors.red),
                        )
                      : const SizedBox()
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

Return null on TextFormField.validator() so the default error style won't be displayed. You can then use a StatefulBuilder so the entire Screen won't be rebuilt when setState() was called.

Demo

Upvotes: 3

Related Questions