DEV Community

Cover image for Flutter Text Field important things you need to know
Mighty
Mighty

Posted on • Edited on • Originally published at mightytechno.com

Flutter Text Field important things you need to know

In Flutter, you can use the TextField widget to get user inputs. Also, it contains different properties to adjust look and feel of the TextField. But when using TextField there will be some pain point to solve. You will find solutions with examples for those pain point from this article.

Set the initial value to text field

Most of the developers have a requirement to set the initial value to the text field like showing edit view to initial fields. But in Flutter there is no property in textField widget to set the initial value. But you can use a controller to set that initial Value.

When initializing controller you can set the value to text property. Then that value will appear as an initial value in the text field. You can initialize controller in initState or you can set text property in initState.

      TextEditingController controller;

       @override
          void initState() {
            super.initState();
            controller = TextEditingController(text: "Initi");

       }

         @override
          Widget build(BuildContext context) {
            return Container(
              child: TextField(
                controller: controller,
              ),
            );
          }
Enter fullscreen mode Exit fullscreen mode

Validate input with Input Formatter

inputFormatter property will allow specifying what kind of input need to accept by input fields. inputFormatter accept list of TextInputFormatter. In here we use WhitelistingTextInputFormatter class to specify the whitelisted characters. Also, you can use BlacklistingTextInputFormatter class to specify the restricted characters.

    @override
          Widget build(BuildContext context) {
            return Container(
              child: TextField(
                controller: controller,
                inputFormatters: [WhitelistingTextInputFormatter(RegExp("[A-Z]"))],
              ),
            );
          }
Enter fullscreen mode Exit fullscreen mode

Multi-line text field

The default text field is configured to be a single line. But we can change this by setting maxLines property to null. Then the text field will be expanded based on the content

 @override
          Widget build(BuildContext context) {
            return Container(
              child: TextField(
                controller: controller,
                TextField(
                  controller: controller,
                  maxLines:null
                )
              ),
            );
          }

Enter fullscreen mode Exit fullscreen mode

Multi-line text field

Validation and add an error message

Fluter provides an inbuilt way of adding a nice error message to input fields. For that first, you need to set InputDecoration for decoration property and InputDecoration will allow setting errorText property.

If we directly set an errorText it will appear all the times. Also, Fluter will make text and border to the red when you set error text.

As an example, in here I will validate the text when onChange occur and based on that you can set errorText property a null or a text.

          TextEditingController controller;
          bool isNameValid = true;
          RegExp regExp = new RegExp(r'^[a-zA-Z]+$',);

          @override
          void initState() {
            super.initState();
            controller = TextEditingController();
          }

          @override
          Widget build(BuildContext context) {
            return Container(
              child: Center(
                child: TextField(
                  onChanged: (value){
                    if(regExp.hasMatch(value)){
                        isNameValid = true;
                    } else {
                        isNameValid = false;
                    }
                    setState(() {

                    });
                  },
                  decoration: InputDecoration(
                    labelText: "Enter Name",
                    errorText: isNameValid ? null : "Invalid name"
                  ),
                  controller: controller,
                ),
              ),
            );
          }

Enter fullscreen mode Exit fullscreen mode

Validation and add an error message

Remove text field underline while keeping a hint

You can set border none to remove the underline and set labeltext to show the hind

 TextField(
                decoration: InputDecoration(
                  border: InputBorder.none,
                  labelText: "First Name",
                ),
                controller: controller,
              )
Enter fullscreen mode Exit fullscreen mode

Change Input type like number,email

Mobile natively support to show the different layout for different input fields like showing number pad for number input and show text keyboard to text input. In Flutter, you can set preferred input type by setting keyboardType property.

 TextField(
                keyboardType: TextInputType.number,
                controller: controller,
              )
Enter fullscreen mode Exit fullscreen mode

Change Input type flutter

Text Field inside Row

You can't just put TextField inside Row and it will not render. Because Row widget needs to know the size of the child elements. Therefore you can wrap the Flexible widget and it will work like charm.

   Row(
      children: <Widget>[
                Flexible(
                  child: new TextField(
                    decoration: InputDecoration(
                      labelText: "First Name",
                    ),
                  ),
                )
              ],
            )

Enter fullscreen mode Exit fullscreen mode

Conclusion

I hope you get answers for some pain point when using the text field in a flutter. If you have any questions please mention in below

Originally published at mightytechno

Connect with me - Instagram |Blog |Youtube(https://twitter.com/mightytechno)

Top comments (2)

Collapse
 
luisgmoreno profile image
Luigui Moreno

Do you know how to "debounce" the onChanged callback?

Collapse
 
mightytechno profile image
Mighty

I haven't tried. I will share If anything found