How to use InputFormatter on Flutter TextField?

2020-02-26 08:05发布

问题:

What do I need to insert into TextField(inputFormatters:?

I want to disallow \ and / in one TextField and only allow a to Z in another.

回答1:

Formatters

In the services library you will find the TextInputFormatter abstract class (this means that you have to import package:flutter/services.dart).

It already has two implementations, which are BlacklistingTextInputFormatter and WhitelistingTextInputFormatter.

If you want to implement your own formatter, you can do so by extending TextInputFormatter itself and implementing formatEditUpdate in there.

I will show how to apply the two premade formatters with given context.

Examples

disallow \ and /

For this we are going to use the BlacklistingTextInputFormatter:

TextField(inputFormatters: [
            BlacklistingTextInputFormatter(RegExp("[/\\\\]")),
          ])

For the Pattern, which needs to be supplied to the formatter, I will be using RegExp, i.e. regular expressions. You can find out more about that here, which also links you to the features I will be using in my examples.

Pay attention to the quadruple backslash \\\\. This represents only a single backslash in reality. The reason for this is that in Dart backslashes are escape keys and a double backslash then respresents a single one and that is the same for RegExp, where backslashes are escape keys as well.

So if we were to block a, b, F, ! and ., we would also put it in a list [...] like this:

BlacklistingTextInputFormatter(RegExp("[abF!.]"))

This translates to "blacklist all 'a', 'b', 'F', '!' and '.'".

only allow a to Z

This time we use the WhitelistingTextInputFormatter:

TextField(inputFormatters: [
            WhitelistingTextInputFormatter(RegExp("[a-zA-Z]")),
          ])

For this we are specifying two ranges of characters: a-z and A-Z, which will also accept all the characters (here all the letters) in between those two specified. This will also work for 0-9 and you can append any character to that list, e.g. a-zA-Z0-9!. will also take ! and . into account.

We can combine this

TextField(inputFormatters: [
            WhitelistingTextInputFormatter(RegExp("[a-zA-Z]")),
            BlacklistingTextInputFormatter(RegExp("[abFeG]")),
          ])

This is only to show that inputFormatters takes a List<InputFormatter>. In reality you should solve this with one whitelist and a regular expression, but this does work as well.



回答2:

import 'package:flutter/services.dart';

use these parameters in the TextFormField... maxLength: 5, keyboardType: TextInputType.number, inputFormatters: [WhitelistingTextInputFormatter.digitsOnly,],



标签: dart flutter