Digit only TextFormField in Flutter

FlutterDart

Flutter Problem Overview


Im am working on an app that requires a price input in ¥ and as such has no decimal places. If we use keyboardType: TextInputType.numberWithOptions() we can get a number pad input. If we use validator: (input) { } we can check if input is valid but we cannot prevent it.

The problem is we can save a draft that will not need validation. So it is better for us to only allow digit input in the first place.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Digits Only',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextFormField(
              autovalidate: true,
              keyboardType: TextInputType.number,
              validator: (input) {
                final isDigitsOnly = int.tryParse(input);
                return isDigitsOnly == null
                    ? 'Input needs to be digits only'
                    : null;
              },
            ),
          ],
        ),
      ),
    );
  }
}

Is there a way to prevent certain text input and only allow digits?

Flutter Solutions


Solution 1 - Flutter

Yep, you can use the inputFormatters attribute and add the WhitelistingTextInputFormatter.digitsOnly expression

  import 'package:flutter/services.dart';


  TextFormField(
          ...
          inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
        )

You can find more info here: https://docs.flutter.io/flutter/services/TextInputFormatter-class.html

After flutter 1.12, WhitelistingTextInputFormatter was deprecated and you are running a newer version, use :

FilteringTextInputFormatter.digitsOnly

https://api.flutter.dev/flutter/services/FilteringTextInputFormatter-class.html

Solution 2 - Flutter

With WhitelistingTextInputFormatter deprecated and using a double number:

keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [FilteringTextInputFormatter.allow(RegExp('[0-9.,]+')),],
onChanged: (value) => doubleVar = double.parse(value),

RegExp('[0-9.,]+') allows for digits between 0 and 9, also comma and dot.

You can use RegExp('([0-9]+(\.[0-9]+)?)') to allow digits and only one dot. See explanation here.

double.parse() converts from string to double.

Don't forget you need: import 'package:flutter/services.dart';

Solution 3 - Flutter

An update on or after April 2021:

TextField(
   inputformatter: [
      FilteringTextInputFormatter.digitsOnly,
      ],
   textInputType: TextInputType.number,

Other examples of the use of input formatters include:

TextField(
  inputFormatters: [
    FilteringTextInputFormatter.deny(RegExp(r'[/\\]')),
  ],
)

OR

inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^ ?\d*')),]
   inputFormatters: [FilteringTextInputFormatter.deny(' ')]

OR

Other options include:

> lowercase letters: a-z
> capital letters: A-Z
> lowercase vowels accented: á-ú
> capital vowels accented: Á-Ú
> numbers: 0-9
> space : (space)

So in the above case you can have

inputFormatters: [
        WhitelistingTextInputFormatter(RegExp("[a-z A-Z á-ú Á-Ú 0-9]"))
      ]

Solution 4 - Flutter

If I am not getting you wrong simply use it keyboardType: TextInputType.number, in textfield.

Solution 5 - Flutter

We need two components:

  1. InputFormatters

    This is the main trick inside the digits only keyboard. You can set its WhitelistingTextInputFormatter property as digitsOnly.

    You need to import services.dart file at first for working this keyboard.

    TextFormField(
      ...
      inputFormatters: <TextInputFormatter>[
        WhitelistingTextInputFormatter.digitsOnly
      ],
    );
    
  2. KeyboardType

    Which shows keyboard with number type, but this is not enough because this keyboard may contain symbols as well as you can convert keyboard into normal character contained keyboard.

    keyboardType: TextInputType.number,
    

With both components will be like this

TextField(
    keyboardType: TextInputType.number,
    inputFormatters: <TextInputFormatter>[
      WhitelistingTextInputFormatter.digitsOnly
    ],
);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEoinView Question on Stackoverflow
Solution 1 - FlutterdiegoveloperView Answer on Stackoverflow
Solution 2 - FlutterPaulo BeloView Answer on Stackoverflow
Solution 3 - FlutterHezView Answer on Stackoverflow
Solution 4 - FlutterDeveloper View Answer on Stackoverflow
Solution 5 - FlutterParesh MangukiyaView Answer on Stackoverflow