Search code examples
flutterflutter-layoutflutter-web

How can I place maxLength in TextFormField in Flutter?


Currently, the limit counter is placed below, but I would like to have it inside the TextFormField at the end. How can I do that?

        child: TextFormField(
                      controller: nameController,
                      maxLength: 50,
                      validator: (String? value) {
                        if (value!.trim().isEmpty) {
                          return 'error';
                        }
                        return null;
                      },
                      onSaved: (String? value) {
                        name = value!.trim();
                      },
                    ),

Solution

  • According to the documentation for the maxLength property on a TextFormField, you have no control over where that is displayed. You can set up a similar counter using the onChanged property of the TextFormField and the suffixText property of the inputDecorator property of the TextFormField (documentation). This requires that the TextFormField be part of a StatefulWidget.

    String counterStr = "0";
    ....
    child: TextFormField(
                      controller: nameController,
                      maxLength: 50,
                      inputDecorator: InputDecorator(
                        suffixText: counterStr
                      ),
                      validator: (String? value) {
                        if (value!.trim().isEmpty) {
                          return 'error';
                        }
                        return null;
                      },
                      onSaved: (String? value) {
                        name = value!.trim();
                      },
                      onChanged: (){
                        setState((){
                          counterStr = nameController.text.length.toString();
                        });
                      }
                    ),