How to Use Flutter Text Field: A Complete Guide for Beginners

Flutter text field is an essential widget that allows users to enter text in a mobile app. As a beginner, understanding how to use text fields in your Flutter app is crucial. 

In this blog post, you'll learn everything you need to know about Flutter text fields, from creating a basic text field to implementing advanced features such as input validation and formatting. 

SimpleTextField Widget in Flutter

The SimpleTextField widget is a custom text input field in Flutter that provides additional features and customizations beyond the standard TextField widget. 

It has properties for setting text input type, hint text, error text, prefix icon, text color, background color, and border radius, among others. It also has validation capabilities that can be used to check user input and provide confirmation or error messages.


Properties:

controller (required): The TextEditingController that controls the text field's content.


hintText: The hint text that appears when the text field is empty.


keyboardType: The type of keyboard to display for input.


obscureText: Whether the text should be obscured, e.g., for password fields.


onChanged: A callback function that is called when the text in the field changes.


helperText: Additional helper text that appears below the text field.


labelText: The label text that appears above the text field.


maxLines: The maximum number of lines the text field can expand to.


hasError: A boolean value indicating whether the field should display an error style.


prefixIconData: An icon that appears before the text field.


passwordHideIcon: The icon to display when the password is obscured and can be used to toggle the visibility of the password.


passwordShowIcon: The icon to display when the password is visible and can be used to toggle the visibility of the password.


textInputAction: The action to take when the user submits the text input.


textColor: The color of the text in the text field.


accentColor: The accent color used for the label text, prefix icon, and other accent elements.



  • Use this helper widget for text field : 
util / common_text_field.dart


import 'package:flutter/material.dart';

class CommonTextField extends StatefulWidget {
  final TextEditingController controller;
  final String? hintText;
  final TextInputType? keyboardType;
  final bool obscureText;
  final Function(String)? onChanged;
  final String? helperText;
  final String? labelText;
  final int? maxLines;
  final bool hasError;
  final IconData? prefixIconData;
  final IconData? passwordHideIcon;
  final IconData? passwordShowIcon;
  final TextInputAction? textInputAction;
  final Color? textColor;
  final Color? accentColor;

  const CommonTextField({
    Key? key,
    required this.controller,
    this.hintText,
    this.keyboardType,
    this.obscureText = false,
    this.onChanged,
    this.helperText,
    this.labelText,
    this.hasError = false,
    this.prefixIconData,
    this.passwordHideIcon,
    this.passwordShowIcon,
    this.textInputAction,
    this.textColor,
    this.maxLines = 1,
    this.accentColor,
  }) : super(key: key);

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

class _CommonTextFieldState extends State<CommonTextField> {
  bool _isObscure = false;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return TextField(
      controller: widget.controller,
      keyboardType: widget.keyboardType,
      obscureText: _isObscure,
      onChanged: widget.onChanged,
      textInputAction: widget.textInputAction,
      maxLines: !_isObscure ? widget.maxLines : 1,
      style: TextStyle(color: widget.textColor ?? Colors.black), // Set text color
      decoration: InputDecoration(
        hintText: widget.hintText,
        labelText: widget.labelText ?? 'Default Simple TextField', // Use confirmation text as label if provided, else use default label text
        labelStyle: TextStyle(color: widget.accentColor ?? Colors.black), // Set accent color
        helperText: widget.helperText,
        prefixIcon: widget.prefixIconData != null
            ? Icon(widget.prefixIconData, color: widget.accentColor ?? theme.colorScheme.primary) // Set accent color for prefix icon
            : null,
        suffixIcon: widget.obscureText
            ? IconButton(
          onPressed: () {
            setState(() {
              _isObscure = !_isObscure;
            });
          },
          icon: Icon(_isObscure ? widget.passwordShowIcon ?? Icons.visibility : widget.passwordHideIcon ?? Icons.visibility_off),
          color: widget.accentColor ?? theme.colorScheme.primary,
        )
            : null,
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(color: theme.primaryColor, width: 1),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(color: theme.colorScheme.secondary, width: 2),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(color: theme.disabledColor, width: 1),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: const BorderSide(color: Colors.red, width: 1),
        ),
        focusedErrorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: const BorderSide(color: Colors.red, width: 2),
        ),
        // You can add more customization to the decoration as needed
        // For example, adding icons, labels, etc.
      ),
    );
  }
}

How to use SimpleTextField widget demo:

view/ demo_text_field.dart


import 'package:flutter/material.dart';

class ContactFormDemo extends StatefulWidget {
  const ContactFormDemo({super.key});

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

class ContactFormDemoState extends State<ContactFormDemo> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _messageController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Common Text field Demo')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Name Field
            CommonTextField(
              controller: _nameController,
              hintText: 'Enter your name',
              labelText: 'Name',
              prefixIconData: Icons.person,
              textInputAction: TextInputAction.next,
            ),
            const SizedBox(height: 16),


            // Password Field
            CommonTextField(
              controller: _passwordController,
              hintText: 'Enter your password',
              labelText: 'Password',
              prefixIconData: Icons.password,
              obscureText: true,
              textInputAction: TextInputAction.next,
            ),
            const SizedBox(height: 16),

            // Email Field
            CommonTextField(
              controller: _emailController,
              hintText: 'Enter your email',
              labelText: 'Email',
              keyboardType: TextInputType.emailAddress,
              prefixIconData: Icons.email,
              textInputAction: TextInputAction.next,
            ),
            const SizedBox(height: 16),

            // Message Field
            CommonTextField(
              controller: _messageController,
              hintText: 'Enter your message',
              labelText: 'Message',
              maxLines: 4,
              prefixIconData: Icons.message,
              textInputAction: TextInputAction.done,
            ),
            const SizedBox(height: 16),

            ElevatedButton(
              onPressed: () {
                // Submit the form
                String name = _nameController.text;
                String password = _passwordController.text;
                String email = _emailController.text;
                String message = _messageController.text;
                print('Name: $name,Password: $password Email: $email, Message: $message');
              },
              child: const Text('Submit'),
            ),
          ],
        ),
      ),
    );
  }
}

..

Comments