Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter TextField input only decimal numbers

I want to input only decimal number in TextField in Flutter. I tried below code but that's not working. It allows alpha (a-z) and special characters.

TextField(
  controller:
      new TextEditingController(text: listDisplay[position].getBlockQty(),
  ),       
  textAlign: TextAlign.center,
  maxLines: 1,       
  keyboardType: TextInputType.numberWithOptions(
      decimal: true,
      signed: false),       
),
like image 874
Sagar Zala Avatar asked Apr 11 '19 11:04

Sagar Zala


People also ask

How do you make a TextField only accept numbers in Flutter?

The TextField widget is required to set keyboardType: TextInputType. number, and inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter. digitsOnly] to accept numbers only as input.

How do you add input field numbers in Flutter?

Flutter does not provide a predefined input for numbers. However, we can use the capabilities of a TextField (or TextFormField ) to mimic the behavior we want a number input to have. It's as simple as changing the keyboard to one that only provides numbers and the allowed characters to digits only.

How do you add two decimals in Flutter?

User can't add more than two digits after the decimal point. You can use TextEditingController to listen for the inputs and manage your logic there.


3 Answers

try this:

inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp(r"[0-9.]")),
        TextInputFormatter.withFunction((oldValue, newValue) {
          try {
            final text = newValue.text;
            if (text.isNotEmpty) double.parse(text);
            return newValue;
          } catch (e) {}
          return oldValue;
        }),
      ],

demo:

TextFormField(
      keyboardType:
          TextInputType.numberWithOptions(decimal: true, signed: false),
      onChanged: _yourOnChange,
      inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp(r"[0-9.]")),
        TextInputFormatter.withFunction((oldValue, newValue) {
          try {
            final text = newValue.text;
            if (text.isNotEmpty) double.parse(text);
            return newValue;
          } catch (e) {}
          return oldValue;
        }),
      ],
    )
like image 81
Chosan Avatar answered Oct 27 '22 20:10

Chosan


You can use TextInputFormatter for this case.

Here is an example for the same,

Subclass TextInputFormatter

import 'package:flutter/services.dart';

class RegExInputFormatter implements TextInputFormatter {
  final RegExp _regExp;

  RegExInputFormatter._(this._regExp);

  factory RegExInputFormatter.withRegex(String regexString) {
    try {
      final regex = RegExp(regexString);
      return RegExInputFormatter._(regex);
    } catch (e) {
      // Something not right with regex string.
      assert(false, e.toString());
      return null;
    }
  }

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    final oldValueValid = _isValid(oldValue.text);
    final newValueValid = _isValid(newValue.text);
    if (oldValueValid && !newValueValid) {
      return oldValue;
    }
    return newValue;
  }

  bool _isValid(String value) {
    try {
      final matches = _regExp.allMatches(value);
      for (Match match in matches) {
        if (match.start == 0 && match.end == value.length) {
          return true;
        }
      }
      return false;
    } catch (e) {
      // Invalid regex
      assert(false, e.toString());
      return true;
    }
  }
}

Use it in with your textfield

final _amountValidator = RegExInputFormatter.withRegex('^\$|^(0|([1-9][0-9]{0,}))(\\.[0-9]{0,})?\$');
...
TextField(
  inputFormatters: [_amountValidator],
  keyboardType: TextInputType.numberWithOptions(
    decimal: true,
     signed: false,
   ),
 )
like image 21
Johnykutty Avatar answered Oct 27 '22 20:10

Johnykutty


I am using this code and it's giving different results , on some phones it shows only numbers and on others it shows dashes and other chars , so it depends on the launcher or something like that i guess, in iPhone i guess it will show the correct keyboard ( i have tried on iPhone 7s plus).

the inputFormatters will allow only numbers so you will get what you want.

   TextField(
     textAlign: TextAlign.start,
     keyboardType: TextInputType.numberWithOptions(decimal: true),
     inputFormatters: <TextInputFormatter>[
                          FilteringTextInputFormatter.digitsOnly
                       ],
   ),
like image 22
redaDk Avatar answered Oct 27 '22 20:10

redaDk