flutter-tutorial

Flutter TextField

Users can type text into text boxes in apps. They’re used to generate forms, send messages, and search experiences, among other things. Learn how to construct and style text fields in this recipe.

TextField and TextFormField are the two text fields provided by Flutter.

TextField

The most popular text input widget is TextField.

An underlining is applied to a TextField by default. By setting the TextField’s decoration attribute to InputDecoration, you can add a label, icon, inline hint text, and error text. Set the decoration to null to delete the entire design (including the underlining and the area reserved for the label).

TextField(
  decoration: InputDecoration(
    border: OutlineInputBorder(),
    hintText: 'Enter a search term',
  ),
),

TextFormField

Wraps a TextField in a TextFormField and integrates it with the enclosing Form. This adds features like validation and integration with other FormField widgets to the mix.

TextFormField(
  decoration: const InputDecoration(
    border: UnderlineInputBorder(),
    labelText: 'Enter your username',
  ),
),

Example:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    const appTitle = 'Learn Code Zone';
    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(appTitle),
        ),
        body: const MyCustomForm(),
      ),
    );
  }
}

class MyCustomForm extends StatelessWidget {
  const MyCustomForm({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        const Padding(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
          child: TextField(
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              hintText: 'Enter a search term',
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
          child: TextFormField(
            decoration: const InputDecoration(
              border: UnderlineInputBorder(),
              labelText: 'Enter your username',
            ),
          ),
        ),
      ],
    );
  }
}

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *