Education
Software Development Executive - II
Last updated on Jul 11, 2024
Last updated on Sep 6, 2023
Flutter Textfield is a prominent element in user interface building, allowing developers to create interactive experiences. Its dynamic design makes it an unparalleled choice for user input processing.
The Flutter TextField is a customizable Text Input Widget in Flutter, where a user inserts alphanumeric data. With just a basic TextField widget, you can start creating search experiences and facilitate user interactions in your app.
The TextField widget forms the building block of many mobile applications. It can considerably enhance user input handling by collecting inputs securely and efficiently. Encapsulated within the text input widget, the TextField performs a variety of tasks, ranging from the collection of personal information to password entries. This widget build area is constructed within the BuildContext context, which allows for a more streamlined interface.
In a Flutter application, you will often come across a Textfield in the class 'MyApp extends StatelessWidget'. The 'build' method in the widget build BuildContext context section is what brings the textfield to life.
1 class MyApp extends StatelessWidget { 2 @override 3 Widget build(BuildContext context) { 4 return MaterialApp( 5 home: Scaffold( 6 appBar: AppBar( 7 title: Text('Flutter TextField Demo'), 8 ), 9 body: TextField(), 10 ), 11 ); 12 } 13 } 14 void main() { 15 runApp(MyApp()); 16 } 17
Above is an example of a simple Flutter application featuring a basic textfield.
Let's go a bit further in the widget build BuildContext context area and explore the TextField widget's properties. Understanding these properties will help you customize the Flutter TextField to your liking.
Before we delve into the properties, here's a Flutter textfield example. We use properties to define inline hint text and label text. The inline hint text and label text serve as instructions on what needs to be entered in the text field.
1 TextField( 2 decoration: InputDecoration( 3 border: OutlineInputBorder(), 4 labelText: 'Enter your username', 5 hintText: 'Username', 6 ), 7 ) 8
In this example code, we've initialized InputDecoration as 'decoration'. This 'decoration property' is used for TextField customization, where we've used it to set initial values like 'border', 'labelText', and 'hintText' for our TextField.
An integral part of creating a complete user experience involves providing users with feedback and directions. These can come in the form of an 'error text' displayed when a user's input does not match the requirements or guidelines in place, or an 'inline hint text' that provides users with an idea of the expected input.
Are you wondering how to kick-start your journey with Flutter Textfield? Let's cut to the chase and create a simple TextField in your new Flutter project. The TextField offers a top-notch user input experience, providing an avenue for the user to input and submit information.
1 import 'package:flutter/material.dart'; 2 3 void main() { 4 runApp(MyApp()); 5 } 6 7 class MyApp extends StatelessWidget { 8 @override 9 Widget build(BuildContext context) { 10 return MaterialApp( 11 home: Scaffold( 12 appBar: AppBar( 13 title: Text('Flutter TextField Demo'), 14 ), 15 body: Center( 16 child: Padding( 17 padding: const EdgeInsets.all(8.0), 18 child: TextField(), 19 ), 20 ), 21 ), 22 ); 23 } 24 } 25
In the snippet above, we have created a basic TextField in Flutter. Locate these changes in your lib folder. We invoked the TextField widget and placed it at the center of our screen with the aid of the Center widget.
Going beyond the edges of basic TextField use, let's implement additional stylings via the InputDecoration class. This class offers rich cosmetic properties that let's customize the TextField as per design needs. The 'decoration inputdecoration' attribute is applied to a TextField to set a border, change the fill color, and set hint text, amongst others.
1 TextField( 2 decoration: InputDecoration( 3 border: OutlineInputBorder(), 4 labelText: 'User Name', 5 hintText: 'Enter your name', 6 ), 7 ), 8
In this example, we have applied InputDecoration in the TextField in Flutter. 'border' is set to OutlineInputBorder(), the 'label text' is User Name, and 'hint text' details what the user should input in this TextField.
A vibrant part of working with a TextField is efficiently using the user's input. For example, you might want to process the text that a user types into a TextField, like their 'user name'. How do you get text from TextField?
This operation is made possible using the TextEditingController which offers the ability to read a TextField value and listen to changes in the text field. Next, we can also set an initial value to the TextField.
1 final myController = TextEditingController(); 2 3 @override 4 void initState() { 5 super.initState(); 6 myController.text = 'initial text'; 7 } 8 9 @override 10 Widget build(BuildContext context) { 11 return TextField( 12 controller: myController, 13 ); 14 } 15
In the code above, we set an initial value to our text field using the controller method. A text value can be extracted from the TextEditingController.
Moving on to the more visually appealing aspects of the Flutter Textfield, refining the look and feel of the TextField is crucial for good user interaction. A TextField in Flutter comes unstyled. A TextField design can be customized using the 'style property'.
1 TextField( 2 style: TextStyle( 3 fontSize: 22, 4 color: Colors.deepOrange, 5 ), 6 ), 7
In the code block above, we modified the font size and color of the text entered into the text box.
A TextField alone can't provide complete user experiences. Often, it's combined with buttons, for example, a "sign in" button. Comes the power of the ElevatedButton Widget:
1 ElevatedButton( 2 onPressed: () { 3 // Do something when the 'sign in' button is pressed 4 }, 5 child: Text('Sign in'), 6 ), 7
Buttons provoke action in a Flutter Application, they're used to finalize entries, cancel operations, or even open a dialog box.
Tackling more specific scenarios, alphanumeric data entry is a common requirement. Like username fields, password fields also collect alphanumeric data, but there's a difference- the TextField obscures the text entered.
If you're wondering about 'textfield obscure' scenarios, here's how you can obscure text:
1 TextField( 2 obscureText: true, 3 ), 4
In the Flutter code above, the 'obscurable text' ensures that the user's password is hidden as they type for added security.
Adding more richness to a TextField can be accomplished by enabling the entry of text in more than one line. By default, TextField handles only one line at a time. However, with a simple variable modulating, TextField can allow text input that spans more than one line.
1 TextField( 2 keyboardType: TextInputType.multiline, 3 maxLines: null, 4 ), 5
The number of lines to be entered into a TextField can be controlled by the attribute maxLines.
Validations shape the backbone of any form, where your Flutter app asks users for input. One of the most fundamental sections within a Flutter app is to validate user input in the TextField. With the validation function, the TextField can provide real-time feedback to users.
The errorText attribute on the TextField displays when the validation fails. See the validating function below:
1 TextField( 2 decoration: InputDecoration( 3 labelText: 'Enter your username', 4 errorText: _validateValue(value) ? 'Value can\'t be empty' : null, 5 ), 6 ), 7
In the Flutter TextField example code above, we've configured a simple validation. It shows an error message if the TextField is left empty.
As we navigate through the practical aspects of a TextField in Flutter, there's a host of other features and methods that aid in creating dynamic user experiences.
Let's explore them with some sample code:
1 class MyApp extends StatelessWidget { 2 final TextEditingController _controller = TextEditingController(); 3 4 @override 5 Widget build(BuildContext context) { 6 return Scaffold( 7 appBar: AppBar(title: Text('Flutter TextField Example')), 8 body: Column( 9 children: [ 10 TextField( 11 controller: _controller, 12 onSubmitted: (String value) async { 13 await showDialog<void>( 14 context: context, 15 builder: (BuildContext context) { 16 return AlertDialog( 17 title: const Text('Thanks!'), 18 content: Text ('You typed "$value", which has ${value.length} characters.'), 19 actions: <Text>[ 20 TextButton( 21 onPressed: () { Navigator.pop(context); }, 22 child: const Text('OK'), 23 ), 24 ], 25 ); 26 }, 27 ); 28 }, 29 decoration: InputDecoration( 30 labelText: 'TextField', 31 hintText: 'Enter some text', 32 border: OutlineInputBorder(), 33 ), 34 ), 35 RaisedButton( 36 onPressed: () => _controller.clear(), 37 child: Text('Clear Text'), 38 ), 39 ], 40 ), 41 ); 42 } 43 } 44 45 void main() { 46 runApp( 47 MaterialApp( 48 home: MyApp(), 49 ), 50 ); 51 } 52
In this Flutter TextField example, we added an onSubmitted method to the TextField, which triggers an alert dialog when the user presses the 'OK' button after typing some textual input.
While we dive deeper into TextField, you'll see Flutter's unique capabilities at managing user inputs. By default, the TextField widget will adapt its keyboard type to facilitate the text input better. This action is done by setting the keyboardType property on a TextField.
1 TextField( 2 keyboardType: TextInputType.emailAddress, 3 ), 4
The TextField outlined above will display an email keyboard when selected. This type of 'platform keyboard' is beneficial when expecting a user to input an email address.
The next step is to manage the "Done" button on the keyboard, or as called in Flutter, the textInputAction. For instance, if the TextField is for a single line input, you'd prefer for the "Done" button to close the 'virtual keyboard'.
1 TextField( 2 keyboardType: TextInputType.text, 3 textInputAction: TextInputAction.done, 4 ), 5
In this code snippet, textInputAction is set to TextInputAction.done, so when users are done with the text input and press the "Done" button, the keyboard collapses.
Now consider a comment text box where users may add a quick comment or write a lengthy review. Here, you'd want the TextField to accommodate text spanning multiple lines and grow as text is typed. Here's an 'expandable textfield' example:
1 TextField( 2 keyboardType: TextInputType.multiline, 3 maxLines: null, 4 ), 5
In the example, maxLines is set to null, which triggers the TextField to expand and accommodate as any lines as the user enters.
Integrating icons to your TextField can enhance its expressivity while providing a clear indication of what information is expected. We can modify our TextField to add icons to it.
1 TextField( 2 decoration: InputDecoration( 3 prefixIcon: Icon(Icons.account_circle), 4 labelText: 'User Name', 5 hintText: 'Enter your user name', 6 border: OutlineInputBorder(), 7 ), 8 ), 9
In the TextField detailed above, we added a user account circle icon by setting it to the prefixIcon property of decoration.
Developing user-friendly applications demands detailed attention to error handling. TextField in Flutter comes equipped with comprehensive error handling capabilities. It's often used to provide immediate feedback to the users regarding their input, which enhances the application's usability significantly.
This is how you can set 'error text' in a TextField:
1 TextField( 2 decoration: InputDecoration( 3 errorText: 'Invalid username', 4 ), 5 ), 6
In the code block above, the errorText attribute adds an error message right below the TextField, which can be customized based on different validation protocols.
The InputFormatter in Flutter is another genius invention, providing developers with control over user input. The 'maximum number' of characters that a TextField can accommodate is one such aspect that can be controlled using the maxLength property:
1 TextField( 2 maxLength: 30, 3 ), 4
In the above example, the TextField will support a maximum of 30 characters, which again enhances data validation at the input level.
Creating user-friendly and dynamic form-handling experiences is fundamental in Flutter applications. While we started our exploration with a simple Flutter TextField, we delved into multiple aspects- right from validation to visual aesthetics- that can ensure the development of intuitive and user-centric applications.
TextField in Flutter is a potent tool, and the more knowledge you gather around it, the better professional you can be. We hope this guide was a worthy aid to your learning journey of the TextField in Flutter.
If you're interested in diving deeper into the TextField and the Flutter framework, here are a few resources that might help:
Allow your creativity to take a front seat, and let TextField do the magic! Flutter on!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.