Flutter TextField Tutorial

TextField widgets are used for reading text inputs, like username, password, phone number, email address, etc. from the keyboard. They are one of the most commonly used widgets in Flutter, just like Buttons. Flutter TextField follows the Google’s material design principles and is fully compliant with the material design text-field specifications.

Create a simple TextField

By default, the TextButton component has only a simple line/divider at the bottom. No other decorations are given. Let’s see how the TextField looks in its bare form.

Flutter textfield with default style
Flutter textfield with default style

The following code generated the above output. In the example code, a no-arg constructor is used to prepare the TextField.

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.teal),
      home: Scaffold(
          appBar: AppBar(title: const Text('TextField Example')),
          body: const TextFieldWidget()),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return const Center(
        //Create a text field
        child: TextField()
    );
  }
}

The TextField constructor has many parameters for customization. This widget being one of the most used widgets in all the framework widgets, it indeed has to have as many customizations as the SDK can provide. Click the following code snippet header to view the constructor and all its options;

const TextField({
 Key? key,
 TextEditingController? controller,
 FocusNode? focusNode,
 InputDecoration? decoration = const InputDecoration(),
 TextInputType? keyboardType,
 TextInputAction? textInputAction,
 TextCapitalization textCapitalization = TextCapitalization.none,
 TextStyle? style,
 StrutStyle? strutStyle,
 TextAlign textAlign = TextAlign.start,
 TextAlignVertical? textAlignVertical,
 TextDirection? textDirection,
 bool readOnly = false,
 ToolbarOptions? toolbarOptions,
 bool? showCursor,
 bool autofocus = false,
 String obscuringCharacter = '•',
 bool obscureText = false,
 bool autocorrect = true,
 SmartDashesType? smartDashesType,
 SmartQuotesType? smartQuotesType,
 bool enableSuggestions = true,
 int? maxLines = 1,
 int? minLines,
 bool expands = false,
 int? maxLength,
 MaxLengthEnforcement? maxLengthEnforcement,
 ValueChanged<String>?onChanged,
 VoidCallback? onEditingComplete,
 ValueChanged<String>?onSubmitted,
 AppPrivateCommandCallback? onAppPrivateCommand,
 List<TextInputFormatter>?inputFormatters,
 bool? enabled,
 double cursorWidth = 2.0,
 double? cursorHeight,
 Radius? cursorRadius,
 Color? cursorColor,
 BoxHeightStyle selectionHeightStyle = ui.BoxHeightStyle.tight,
 BoxWidthStyle selectionWidthStyle = ui.BoxWidthStyle.tight,
 Brightness? keyboardAppearance,
 EdgeInsets scrollPadding = const EdgeInsets.all(20.0),
 DragStartBehavior dragStartBehavior = DragStartBehavior.start,
 bool? enableInteractiveSelection,
 TextSelectionControls? selectionControls,
 GestureTapCallback? onTap,
 MouseCursor? mouseCursor,
 InputCounterWidgetBuilder? buildCounter,
 ScrollController? scrollController,
 ScrollPhysics? scrollPhysics,
 Iterable<String>?autofillHints = const<String>[],
 Clip clipBehavior = Clip.hardEdge,
 String? restorationId,
 bool scribbleEnabled = true,
 bool enableIMEPersonalizedLearning = true 
})

Customize the TextField

Let’s learn how to customize the TextField widget with an email input example. We need to make the widget look like the material design TextField with nice rounded borders with label. Let’s also add an email icon.

We will do the following customizations:

  • Set a rounded border with border label
  • Set a hint text
  • Set an email icon at the start position of the TextField
  • Set font size to 18dp
  • Set input type to email so that the virtual keyboard will adjust accordingly (will show @ button)
TextField with Icon in Flutter
Customized TextField in flutter with icon, label, hint and email keyboard-type.
class TextFieldWidget extends StatelessWidget {
  const TextFieldWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: TextField(
        //Set text style
        style: TextStyle(
          fontSize: 18
        ),
        keyboardType: TextInputType.emailAddress, //Set keyboard type for email address. This will show @ button on the primary section of the keyboard.
        //Set decoration
        decoration: InputDecoration(
            border: OutlineInputBorder(), //Create rounded outlined border
            labelText: "Email", //Set the label text that will be shown over the border
            prefixIcon: Icon(Icons.email), // Set email icon at the start of the TextField
            hintText: "Enter your email ID"), // Set the hint text that will be shown when TextField is empty
      ),
    );
  }
}

Retrieve typed text input from TextField

Flutter has multiples ways to get and process text from the TextField widget. The best approach is to use a TextController class to handle all the events coming out of the TextField properly. The simplest approach is to use an onChange() callback.

Also, it is possible to track every change happening on the text field (For example, while entering hello, get callback after each letter h, e, l, l, and o separately). On the other hand, if you are interested only when the text field input is finished and user wants to submit the data, there is a callback method for that as well.

Let’s see all these options in detail.

Tracking every text change in the TextField

First, let’s see how we can track every change happening on the TextField. There are two ways to do this.

  1. Using onChange() callback
  2. TextEditingController

Using onChange() callback – The easy way

onChange() callback can be added by providing it to the TextField constructor. We can provide a function to the onChanged property to register an onChange callback. This will print “Entered value: …..” as soon as we start typing contents to the TextField.

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

  @override
  Widget build(BuildContext context) {
    return Center(
      child: TextField(
        onChanged: (value) {
          print('Entered value: $value');
        },
        style: const TextStyle(fontSize: 18),
        keyboardType: TextInputType.emailAddress,
        decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "Email", prefixIcon: Icon(Icons.email), hintText: "Enter your email ID"),
      ),
    );
  }
}
Flutter TextField onChange callback
Flutter TextField onChange callback firing print output for each keystroke

Using TextEditingController – The best way

Using TextEditingController is recommended since it is easier to use as the text-value from the text field needs to be used on other widgets. For using TextEditingController, we have to do the following steps.

  1. Create a TextEditingController
  2. Create a function that executes whenever the text is changed
  3. Link the function to the TextEditingController inside initState() function. This is for creating the link between controller and function
  4. Dispose the TextEditingController inside dispose() for resource cleanup
  5. Link the controller to the TextField via the controller attribute
import 'package:flutter/material.dart';

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

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

  @override
  State<StatefulWidget> createState() {
    return TextFieldWidget();
  }
}

class TextFieldWidget extends State<TextFieldTutorial> {

  //Create new TextEditingController
  final emailTextFieldController = TextEditingController();

  @override
  void initState() {
    super.initState();
    //Link controller to the function to be executed on change
    emailTextFieldController.addListener(printTextFieldValue);
  }

  @override
  void dispose() {
    //Dispose the controller when the widget is disposed
    emailTextFieldController.dispose();
    super.dispose();
  }

  //Function that executes when the text is changed
  void printTextFieldValue() {
    print('Second text field: ${emailTextFieldController.text}');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: Scaffold(
        appBar: AppBar(title: const Text('TextField Example')),
        body: Padding(
          padding: const EdgeInsets.all(50),
          child: TextField(
            controller: emailTextFieldController, //Link controller to TextField
            style: const TextStyle(fontSize: 18),
            keyboardType: TextInputType.emailAddress,
            decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "Email", prefixIcon: Icon(Icons.email), hintText: "Enter your email ID"),
          ),
        ),
      ),
    );
  }
}

Tracking text submission event with onSubmitted callback

So far, we have seen how to track every text change inside the TextField. Most of the time, we might not be interested in the individual text changes, but on the final text the user submits. Flutter provides a callback for the submission event as well. This callback can be registered through the onSubmitted parameter.

The onSubmitted callback will be fired only when you press the Submit button on the keyboard. In Android and iOS, it is the ‘check’ or ‘tick’ button on the keyboard. On the desktop platform, it is the ENTER key. In the following gif image, you can see that the onSubmitted function is fired only after the check button was pressed.

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

  @override
  Widget build(BuildContext context) {
    return Center(
      child: TextField(
        onSubmitted: (submittedValue) {
          print('Submitted value: $submittedValue');
        },
        style: const TextStyle(fontSize: 18),
        keyboardType: TextInputType.emailAddress,
        decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "Email", prefixIcon: Icon(Icons.email), hintText: "Enter your email ID"),
      ),
    );
  }
}
Flutter TextField onSubmitted callback
Flutter TextField onSubmitted callback example

Example program: Change label value automatically when TextField text is changed

Let’s apply what we have learned so far in this chapter into a full example application. The requirement is as follows.

Requirement – There are two widgets in the screen, one “Text” and one “TextField” widget. Automatically update label/text component value when the input on the TextField is changed.

The solution for the problem is given below.

import 'package:flutter/material.dart';

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

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

  @override
  State<StatefulWidget> createState() {
    return TextFieldWidget();
  }
}

class TextFieldWidget extends State<TextFieldTutorial> {
  String state = "";

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: Scaffold(
        appBar: AppBar(title: const Text('TextField Example')),
        body: Padding(
          padding: const EdgeInsets.all(50),
          child: Column(children: [
            Text('Entered email address is: $state'), //Set the label text using the state variable
            const SizedBox(height: 20),
            TextField(
              onChanged: (value) {
                setState(() => state = value); //Update state as soon as the TextField text is changed
              },
              style: const TextStyle(fontSize: 18),
              keyboardType: TextInputType.emailAddress,
              decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "Email", prefixIcon: Icon(Icons.email), hintText: "Enter your email ID"),
            ),
          ]),
        ),
      ),
    );
  }
}

The output of the above code snippet is as follows.

Flutter TextField and Label Binding
Flutter TextField and Text Value Binding

Conclusion

In this tutorial, we have learned how to use flutter TextField. We have gone through the customization, callbacks like onChange, onSubmit and text field controller options. If this tutorial was useful, you might be interested in the other Flutter tutorials I have written.

Comments

252 responses to “Flutter TextField Tutorial”

  1. generic tadalafil india

    generic tadalafil india

  2. how to relieve back pain cause by tadalafil

    how to relieve back pain cause by tadalafil

  3. tadalafil 5mg generic

    tadalafil 5mg generic

  4. cialis side effects a wife’s perspective

    cialis side effects a wife’s perspective

  5. ed pharmacy viagra

    ed pharmacy viagra

  6. female viagra pill price in india

    female viagra pill price in india

  7. viagra online buy india

    viagra online buy india

  8. generic for cialis

    generic for cialis

  9. cialis commercial

    cialis commercial

  10. tadalafil troche (lozenge) where to buy

    tadalafil troche (lozenge) where to buy

  11. cialis 5mg best price

    cialis 5mg best price

  12. gabapentin urinary

    gabapentin urinary

  13. metronidazole streptococcus

    metronidazole streptococcus

  14. valtrex hemodialysis

    valtrex hemodialysis

  15. lyrica causes brain damage

    lyrica causes brain damage

  16. metformin eizellqualität

    metformin eizellqualität

  17. lasix wechselwirkungen

    lasix wechselwirkungen

  18. semaglutide tablets rybelsus

    semaglutide tablets rybelsus

  19. what happens when you drink alcohol while taking cymbalta

    what happens when you drink alcohol while taking cymbalta

  20. gabapentin development

    gabapentin development

  21. cephalexin for bronchitis

    cephalexin for bronchitis

  22. ciprofloxacin for std

    ciprofloxacin for std

  23. bactrim for uti 3 days

    bactrim for uti 3 days

  24. … [Trackback]

    […] Find More Information here on that Topic: genuinecoder.com/flutter-textfield-tutorial/ […]

  25. … [Trackback]

    […] Here you will find 94501 more Info to that Topic: genuinecoder.com/flutter-textfield-tutorial/ […]

  26. … [Trackback]

    […] Find More to that Topic: genuinecoder.com/flutter-textfield-tutorial/ […]

  27. amoxicillin rash after 7 days

    amoxicillin rash after 7 days

  28. diltiazem hcl er

    diltiazem hcl er

  29. flomax for a female

    flomax for a female

  30. does augmentin cause diarrhea

    does augmentin cause diarrhea

  31. picture of ezetimibe

    picture of ezetimibe

  32. cozaar and alcohol

    cozaar and alcohol

  33. ddavp injection prescribing information

    ddavp injection prescribing information

  34. does flexeril show up on a drug test

    does flexeril show up on a drug test

  35. depakote 125 mg

    depakote 125 mg

  36. bayer aspirin 81 mg

    bayer aspirin 81 mg

  37. stopping celexa

    stopping celexa

  38. can i take tylenol with celebrex

    can i take tylenol with celebrex

  39. augmentin sinus infection

    augmentin sinus infection

  40. … [Trackback]

    […] Information to that Topic: genuinecoder.com/flutter-textfield-tutorial/ […]

  41. remeron davis pdf

    remeron davis pdf

  42. repaglinide and pioglitazone

    repaglinide and pioglitazone

  43. protonix reviews

    protonix reviews

  44. robaxin side effects dogs

    robaxin side effects dogs

  45. how does tizanidine work

    how does tizanidine work

  46. acarbose effectiveness

    acarbose effectiveness

  47. spironolactone 25 mg tablet

    spironolactone 25 mg tablet

  48. online pharmacy uk

    online pharmacy uk

  49. levitra 10mg price

    levitra 10mg price

  50. uk pharmacy tramadol

    uk pharmacy tramadol

  51. vardenafil brand name

    vardenafil brand name

  52. vardenafil online pharmacy

    vardenafil online pharmacy

  53. where can i buy stromectol

    where can i buy stromectol

  54. tadalafil and tamsulosin and blood pressure

    tadalafil and tamsulosin and blood pressure

  55. stromectol 3 mg dosage

    stromectol 3 mg dosage

  56. gabapentin pregnancy

    gabapentin pregnancy

  57. comparison between ampicillin and amoxicillin

    comparison between ampicillin and amoxicillin

  58. does amoxicillin treat sinus infection

    does amoxicillin treat sinus infection

  59. can you drink alcohol with cephalexin

    can you drink alcohol with cephalexin

  60. how does trazodone make you feel

    how does trazodone make you feel

  61. metformin and eggs

    metformin and eggs

  62. lyrica pill

    lyrica pill

  63. keflex during pregnancy

    keflex during pregnancy

  64. Flutter TextField Tutorial | Genuine Coder

    https://xophia.net/ecommerce-video-news/

  65. Flutter TextField Tutorial | Genuine Coder

    http://runfahs.dk/2015/07/22/hej-verden/

  66. Flutter TextField Tutorial | Genuine Coder

    http://www.z-hypnose.dk/?p=1

  67. find location by phone number

    Simple but effective mobile number tracker. Great for keeping tabs on company devices.

  68. Konya SEO Uzman脹

    Konya SEO uzmanトア, Google’トアn gizli ajanトア olduト殷na inanトアyor.

  69. buy instagram followers

    Quick delivery when I decided to buy Instagram followers. Support team was helpful throughout the process.

  70. Web Sitesi Kurma

    Web sitesi kurma sureci cok profesyonelce ilerledi. Tam istedigim gibi oldu.

  71. cristiano ronaldo skills

    cristiano ronaldo skills hello i am a football player

  72. tramadol hcl online pharmacy

    tramadol hcl online pharmacy

  73. cialis and levitra together

    cialis and levitra together

  74. vardenafil reviews

    vardenafil reviews

  75. vardenafil vs tadalafil vs sildenafil

    vardenafil vs tadalafil vs sildenafil

  76. sildenafil 100mg

    sildenafil 100mg

  77. sildenafil max dose

    sildenafil max dose

  78. sildenafil citrate 50 mg

    sildenafil citrate 50 mg

  79. what is sildenafil used for

    what is sildenafil used for

  80. sildenafil and tadalafil

    sildenafil and tadalafil

  81. can you take tadalafil daily

    can you take tadalafil daily

  82. viagra sale 70 pharmacy online

    viagra sale 70 pharmacy online

  83. erectile dysfunction medications

    erectile dysfunction medications

  84. can cialis cure ed permanently

    can cialis cure ed permanently

  85. telmisartan online pharmacy

    telmisartan online pharmacy

  86. vardenafil hcl canada

    vardenafil hcl canada

  87. tramadol mexico pharmacy

    tramadol mexico pharmacy

  88. uk online pharmacy propecia

    uk online pharmacy propecia

  89. safeway pharmacy soma

    safeway pharmacy soma

  90. online pharmacy store in kolkata

    online pharmacy store in kolkata

  91. tadalafil duration of action

    tadalafil duration of action

  92. how far apart should i take tylenol and ibuprofen

    how far apart should i take tylenol and ibuprofen

  93. celecoxib brand name in pakistan

    celecoxib brand name in pakistan

  94. bula tegretol indicação

    bula tegretol indicação

  95. indomethacin grapefruit

    indomethacin grapefruit

  96. cilostazol prescribing information

    cilostazol prescribing information

  97. mestinon farmacie

    mestinon farmacie

  98. piroxicam actor

    piroxicam actor

  99. sumatriptan without food

    sumatriptan without food

  100. lioresal efecte secundare

    lioresal efecte secundare

  101. houses for sale in pinebrook artane

    houses for sale in pinebrook artane

  102. cyproheptadine urticaria

    cyproheptadine urticaria

  103. zanaflex side effects headache

    zanaflex side effects headache

  104. Flutter TextField Tutorial | Genuine Coder

    http://www.agpconseil.net/contact

  105. […] rybelsus price […]

  106. Flutter TextField Tutorial | Genuine Coder

    https://on-sapo.com/20220101/

  107. Flutter TextField Tutorial | Genuine Coder

    http://fukuesho.jp/contact/

  108. […] voguel sildenafil 100mg […]

  109. […] 20mg cialis daily […]

  110. […] sildenafil citrate 100mg en español […]

  111. cheapest buy enclomiphene generic best price

    get enclomiphene price from cvs

  112. generique kamagra prescrire sun medicament pharmacie

    kamagra canada

  113. discount androxal purchase uk

    order androxal generic for sale

  114. get dutasteride generic medications

    purchase dutasteride cost per tablet

  115. ordering flexeril cyclobenzaprine australia purchase

    buy flexeril cyclobenzaprine purchase from uk

  116. purchase gabapentin usa buying

    how do i get gabapentin from my doctor

  117. cheapest buy fildena australia suppliers

    get fildena cheap store

  118. how to buy itraconazole uk order

    cheap itraconazole generic best price

  119. purchase staxyn no prescription needed

    online order staxyn generic online cheapest

  120. buying avodart generic uk next day delivery

    ordering avodart purchase no prescription

  121. rifaximin weight loss

    cheap rifaximin canada on sale

  122. online order xifaxan generic does it work

    get xifaxan singapore where to buy

  123. nenテュ nutnテス pナ册dpis kamagra

    kamagra a nテ。rナッst tト嬪esnテゥ hmotnosti

  124. […] generic cialis cost […]

  125. […] sildenafil tablets 50mg […]

  126. […] viagra sildenafil 25 mg […]

  127. […] generic viagra 50 mg […]

  128. […] sublingual cialis […]

  129. generic viagra

    generic viagra

  130. lasix medicine for fluid

    lasix medicine for fluid

  131. lasix 40 mg tablet

    lasix 40 mg tablet

Leave a Reply