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.
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)
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.
- Using onChange() callback
- 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"), ), ); } }
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.
- Create a TextEditingController
- Create a function that executes whenever the text is changed
- Link the function to the TextEditingController inside initState() function. This is for creating the link between controller and function
- Dispose the TextEditingController inside dispose() for resource cleanup
- 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"), ), ); } }
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.
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.
generic tadalafil india
generic tadalafil india
how to relieve back pain cause by tadalafil
how to relieve back pain cause by tadalafil
tadalafil 5mg generic
tadalafil 5mg generic
cialis side effects a wife’s perspective
cialis side effects a wife’s perspective
ed pharmacy viagra
ed pharmacy viagra
female viagra pill price in india
female viagra pill price in india
viagra online buy india
viagra online buy india
generic for cialis
generic for cialis
cialis commercial
cialis commercial
tadalafil troche (lozenge) where to buy
tadalafil troche (lozenge) where to buy
cialis 5mg best price
cialis 5mg best price
gabapentin urinary
gabapentin urinary
metronidazole streptococcus
metronidazole streptococcus
valtrex hemodialysis
valtrex hemodialysis
lyrica causes brain damage
lyrica causes brain damage
metformin eizellqualität
metformin eizellqualität
lasix wechselwirkungen
lasix wechselwirkungen
semaglutide tablets rybelsus
semaglutide tablets rybelsus
what happens when you drink alcohol while taking cymbalta
what happens when you drink alcohol while taking cymbalta
gabapentin development
gabapentin development
Flutter TextField Tutorial
http://koriyama-tc.com/school/
Flutter TextField Tutorial
https://murrka.ru/bitrix/rk.php?goto=https://cheapcamshows.com/en/events/jeniffer/
Flutter TextField Tutorial
https://vade-retro.fr/colloque-de-czestochowa-juillet-2007/
Flutter TextField Tutorial
https://www.bajauindonesia.com/potret-nelayan-suku-bajau-desa-langara-tanjung-batu/
cephalexin for bronchitis
cephalexin for bronchitis
ciprofloxacin for std
ciprofloxacin for std
bactrim for uti 3 days
bactrim for uti 3 days
… [Trackback]
[…] Find More Information here on that Topic: genuinecoder.com/flutter-textfield-tutorial/ […]
… [Trackback]
[…] Here you will find 94501 more Info to that Topic: genuinecoder.com/flutter-textfield-tutorial/ […]
… [Trackback]
[…] Find More to that Topic: genuinecoder.com/flutter-textfield-tutorial/ […]
Flutter TextField Tutorial
https://sharevita.com/richard93567?mode=night
amoxicillin rash after 7 days
amoxicillin rash after 7 days
diltiazem hcl er
diltiazem hcl er
flomax for a female
flomax for a female
does augmentin cause diarrhea
does augmentin cause diarrhea
picture of ezetimibe
picture of ezetimibe
cozaar and alcohol
cozaar and alcohol
ddavp injection prescribing information
ddavp injection prescribing information
does flexeril show up on a drug test
does flexeril show up on a drug test
depakote 125 mg
depakote 125 mg
bayer aspirin 81 mg
bayer aspirin 81 mg
stopping celexa
stopping celexa
can i take tylenol with celebrex
can i take tylenol with celebrex
augmentin sinus infection
augmentin sinus infection
… [Trackback]
[…] Information to that Topic: genuinecoder.com/flutter-textfield-tutorial/ […]
remeron davis pdf
remeron davis pdf
repaglinide and pioglitazone
repaglinide and pioglitazone
protonix reviews
protonix reviews
Flutter TextField Tutorial | Genuine Coder
https://directory4web.com/listings12639831/not-known-factual-statements-about-a-luxury-watch
robaxin side effects dogs
robaxin side effects dogs
how does tizanidine work
how does tizanidine work
acarbose effectiveness
acarbose effectiveness
spironolactone 25 mg tablet
spironolactone 25 mg tablet
Flutter TextField Tutorial | Genuine Coder
https://matrixmetal.in/jack-rods-manufacturer-in-ahmedabad-2/
Flutter TextField Tutorial | Genuine Coder
https://judobudan.hu/pin-up-online-casino-azerbaycan-️-onlayn-kazino-pinup-rəsmi-sayt/
Flutter TextField Tutorial | Genuine Coder
https://it-consulting-ebikon.ch/10-ways-to-achieve-your-business-goal/
Flutter TextField Tutorial | Genuine Coder
https://www.pmdinganjuk.com/631-2/comment-page-10493/
online pharmacy uk
online pharmacy uk
levitra 10mg price
levitra 10mg price
uk pharmacy tramadol
uk pharmacy tramadol
Flutter TextField Tutorial | Genuine Coder
https://josenascimento.com/mal-amado5-cpia/
vardenafil brand name
vardenafil brand name
vardenafil online pharmacy
vardenafil online pharmacy
where can i buy stromectol
where can i buy stromectol
tadalafil and tamsulosin and blood pressure
tadalafil and tamsulosin and blood pressure
stromectol 3 mg dosage
stromectol 3 mg dosage
Flutter TextField Tutorial | Genuine Coder
https://azeletminosegert.hu/ez-egy-minta-oldal/
Flutter TextField Tutorial | Genuine Coder
https://www.led-ibc.nl/2023/12/12/nieuwe-e-mail-officewoodpeckers-be/
Flutter TextField Tutorial | Genuine Coder
https://egenbay.com/google-now-discounts-all-reciprocal-links/
Flutter TextField Tutorial | Genuine Coder
https://loovebook.org/2786-karimin-kuzeniyle-seks-yaptim.html
gabapentin pregnancy
gabapentin pregnancy
comparison between ampicillin and amoxicillin
comparison between ampicillin and amoxicillin
does amoxicillin treat sinus infection
does amoxicillin treat sinus infection
can you drink alcohol with cephalexin
can you drink alcohol with cephalexin
how does trazodone make you feel
how does trazodone make you feel
metformin and eggs
metformin and eggs
lyrica pill
lyrica pill
keflex during pregnancy
keflex during pregnancy
Flutter TextField Tutorial | Genuine Coder
https://xophia.net/ecommerce-video-news/
Flutter TextField Tutorial | Genuine Coder
https://terbunenouderraad.be/2019/12/25/ouderraad-ter-bunen-oedelem/
Flutter TextField Tutorial | Genuine Coder
https://www.maximbondarenko.com/ari/
Flutter TextField Tutorial | Genuine Coder
https://flushingtabletennis.com/privacy-policy/
Flutter TextField Tutorial | Genuine Coder
https://everythingisedible.com/does-tiktok-tell-you-who-shared-your-video/
Flutter TextField Tutorial | Genuine Coder
http://runfahs.dk/2015/07/22/hej-verden/
Flutter TextField Tutorial | Genuine Coder
http://www.biyolokum.com/2009/03/sansurden-sonra-gelismeler/
Flutter TextField Tutorial | Genuine Coder
http://www.crimson-sleep.de/mainf.php?url=https://cheapcamshows.com
Flutter TextField Tutorial | Genuine Coder
https://mysocialclub.ru/prikols/page,1,31,5922-prikoly-onlayn.html
Flutter TextField Tutorial | Genuine Coder
http://logre.fr/cest-le-nouveau-site-de-logre/
Flutter TextField Tutorial | Genuine Coder
https://www.dipolo-gmbh.de/de/component/k2/case-study-sram.html?start=1360
Flutter TextField Tutorial | Genuine Coder
https://nexushumanpharmaceuticals.com/patientcentered-hospital-labs-start-here/
Flutter TextField Tutorial | Genuine Coder
https://gameking.com.au/machines-on-free-play-the-technology-and-creativity-of-game-vending-machines/
Flutter TextField Tutorial | Genuine Coder
https://www.granosdearena.org/we-hear-your-prayers/
Flutter TextField Tutorial | Genuine Coder
https://www.studiorao.it/category/approfondimenti/
Flutter TextField Tutorial | Genuine Coder
http://plumbers-builders.co.uk/all-posts/praesent-vestibulum-molestie-lacus-3/
Flutter TextField Tutorial | Genuine Coder
https://cam-info.com/complementar-vs-alternative-medicine/
Flutter TextField Tutorial | Genuine Coder
https://mayar.ae/together-we-standtogether-we-succeed/
Flutter TextField Tutorial | Genuine Coder
https://cifar.it/curabitur-convallis-nisi-ultricies/
Flutter TextField Tutorial | Genuine Coder
http://www.z-hypnose.dk/?p=1
Flutter TextField Tutorial | Genuine Coder
https://photos.teblunthuis.cc/picture.php?/534/most_visited/start-10
Flutter TextField Tutorial | Genuine Coder
https://lekashmir.fr/histoire-culinaire/tandoor/
Flutter TextField Tutorial | Genuine Coder
http://www.lookround.net/forums/forum/romantic/
Flutter TextField Tutorial | Genuine Coder
http://goe.sk/2017/11/22/borsky-mikulas/
Flutter TextField Tutorial | Genuine Coder
https://mondemenageur.net/moving-checklist/
Flutter TextField Tutorial | Genuine Coder
https://bornakombucha.com/علائم-و-درمان-اختلالات-جنسی/
Flutter TextField Tutorial | Genuine Coder
https://myniche.eu/wat-is-jouw-favoriete-affirmatie-voor-een-evenwichtig-leven/
Flutter TextField Tutorial | Genuine Coder
http://www.100auc.info/gotoURL.asp?url=https://cheapcamshows.com/
Flutter TextField Tutorial | Genuine Coder
https://muneera-alhamad.com/دفاتر-فارغة/
Flutter TextField Tutorial | Genuine Coder
https://www.topmodernfurniture.com/high-quality-beds-at-low-prices:-our-top-picks/
find location by phone number
Simple but effective mobile number tracker. Great for keeping tabs on company devices.
Konya SEO Uzman脹
Konya SEO uzmanトア, Google’トアn gizli ajanトア olduト殷na inanトアyor.
buy instagram followers
Quick delivery when I decided to buy Instagram followers. Support team was helpful throughout the process.
Web Sitesi Kurma
Web sitesi kurma sureci cok profesyonelce ilerledi. Tam istedigim gibi oldu.
cristiano ronaldo skills
cristiano ronaldo skills hello i am a football player
Flutter TextField Tutorial | Genuine Coder
http://buurtverenigingdeeendracht.nl/index.php/2017/04/07/fotos/
Flutter TextField Tutorial | Genuine Coder
http://www.lavoce.co.kr/sub/sub07_01.php?boardid=news
Flutter TextField Tutorial | Genuine Coder
https://mercycollective.org/why-do-christians-keep-the-sabbath/
Flutter TextField Tutorial | Genuine Coder
http://avalierconcepts.com/2022/05/18/digital-marketing-expectations/
Flutter TextField Tutorial | Genuine Coder
https://conferencesolutions.co.ke/how-important-is-light-in-the-living-room/
Flutter TextField Tutorial | Genuine Coder
https://livewell-group.com/product/conforming-bandage/
Flutter TextField Tutorial | Genuine Coder
https://www.biztipstricks.com/2023/04/12/why-digital-marketing-services-are-crucial-for-business-success-in-the-digital-age/
Flutter TextField Tutorial | Genuine Coder
https://platinaker.hu/ezek-a-szinek-lesznek-a-2021-es-ev-trendszinei/