Flutter Community

Creating an Input Formatter for Chunking Text Input in Flutter

thumbnail

Table of Contents

  1. Introduction
  2. Formatting a String with Spaces
  3. Calculating the Selection Offset with Spaces

1. Introduction

In this article, we tackle the issue of creating an Input Formatter for chunking text input in Flutter. Specifically, we focus on creating a formatter for IBAN input that automatically inserts spaces while maintaining the natural behavior of text selection offsets.

2. Formatting a String with Spaces

The IBAN formatter function takes the new value's text as a string input and formats it according to the standard IBAN format. For example, it formats the text as "DE12 3456 7890 1234 5678 90" for a German IBAN with 27 characters.

3. Calculating the Selection Offset with Spaces

To ensure that the text selection offset accounts for the spaces in the formatted IBAN, a function is implemented. This function adjusts the offset based on the changes in the text caused by inserting or removing spaces. The key steps include:

  • Checking if the new offset exceeds the new text length or if the previous offset was beyond the new length.
  • Handling scenarios where the cursor position was at the end of the field.
  • Calculating the difference in spaces added or removed to adjust the offset accordingly.
  • Considering cases where a digit is removed after a space and adjusting the offset accordingly.

By incorporating this functionality into the input formatter, text input fields in Flutter can handle IBAN formatting with automatic offset adjustment seamlessly.

This solution provides a comprehensive approach to handling text input formatting challenges in Flutter, offering a practical solution for implementing specialized input formatters for various text formats.