In Flutter, limiting the input length of text fields is a common requirement, and we commonly utilize the maxLength property of TextField to achieve this. The maxLength property restricts the number of characters the user can input into the text field. For example, if you want users to input a maximum of 20 characters in a text input field, you can set it as follows:
dartTextField( maxLength: 20, )
Additionally, TextField includes a property called maxLengthEnforced, which is a boolean value determining whether to prevent further input once the text reaches the maximum length. By default, maxLengthEnforced is set to true, meaning users cannot continue typing once the input reaches the limit specified by maxLength. If you set it to false, users can continue typing, but the excess content will not be displayed in the text field.
In some cases, more complex input restrictions are needed, such as limiting character types or formats (e.g., phone numbers, email addresses). For these scenarios, we can combine the use of TextEditingController and InputFormatter. Here is an example using TextInputFormatter to restrict input to only digits:
dartimport 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class NumericTextField extends StatelessWidget { final TextEditingController controller; NumericTextField({Key? key, required this.controller}) : super(key: key); Widget build(BuildContext context) { return TextField( controller: controller, keyboardType: TextInputType.number, inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly ], ); } }
In this example, setting keyboardType to TextInputType.number optimizes the keyboard for numeric input. Furthermore, FilteringTextInputFormatter.digitsOnly ensures only digits can be entered. This approach is highly effective for scenarios requiring input format restrictions.