flutter
  1. flutter-textfield

Flutter TextField

A TextField is a widget that allows users to enter and edit text. It is one of the most commonly used input widgets in Flutter.

Syntax

TextField(
  controller: controller,
  decoration: InputDecoration(
    labelText: 'Label',
    hintText: 'Hint Text',
    prefixIcon: Icon(Icons.person),
    suffixIcon: IconButton(
      icon: Icon(Icons.clear),
      onPressed: () => controller.clear(),
    ),
  ),
  onChanged: (value) {
    // Do something with the value
  },
)

Example

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _textController = TextEditingController();

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter TextField'),
      ),
      body: Center(
        child: TextField(
          controller: _textController,
          decoration: InputDecoration(
            labelText: 'Enter your name',
            prefixIcon: Icon(Icons.person),
          ),
          onChanged: (value) {
            print('Value changed: $value');
          },
        ),
      ),
    );
  }
}

Output

The above example will display a screen with a text field that looks like this:

Flutter TextField Example

Explanation

  • In the TextField widget, we pass in a controller to control the text field.
  • The decoration property is used to configure the appearance of the text field - in this example, we set a label, hint text, and add icons.
  • The onChanged callback is triggered whenever the text in the field changes.

Use

Use a TextField widget to accept user input of text values in a Flutter application.

Important Points

  • The TextField widget in Flutter requires a controller to be used to monitor and manipulate the text entered in the field.
  • Use the decoration property to configure the appearance of the text field.
  • The keyboardType property can be used to specify the type of keyboard to show when the text field is focused.

Summary

A TextField widget is used to accept text input from users in Flutter applications. Its appearance and behavior can be customized using the decoration property. Always use a controller to monitor and manipulate the text entered in the TextField.

Published on: