Digit only TextFormField in 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';
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]"))
]
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