Flutter: KeyboardType attribute not working as expected in TextFormField ,still can paste text.how to change input type?(Flutter)

4,126

Solution 1

You can try to use WhitelistingTextInputFormatter like

inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],

See official docs

Solution 2

The accepted answer is now deprecated as of Flutter version 1.20.0-1.0.pre. Now, use inputFormatters: [FilteringTextInputFormatter.digitsOnly], instead (see documentation).

In addition, if you want finer control onto what to input using RegEx, use FilteringTextInputFormatter.allow(RegExp(r'your regex here')).

Share:
4,126
MohanKumar
Author by

MohanKumar

A Tech explorer who loves to learn new technologies.Working as a android developer loves to learn and help others more on it.

Updated on December 14, 2022

Comments

  • MohanKumar
    MohanKumar over 1 year

    I am using a TextFormField to get a number as input so i used this snippet

    keyboardType: TextInputType.number,
    

    This is my TextFormField Widget code

             TextFormField(
                      keyboardType: TextInputType.number,
                      style: textstyle,
                      controller: principal,
                      validator: (String value) {
                        if (value.isEmpty) {
                          return "Please enter principal amount e.g 3245";
                        }
                      },
                      decoration: InputDecoration(
                          labelText: "Principal",
                          labelStyle: textstyle,
                          hintText: "Rupees",
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5.0))),
                    )
    

    But now i can paste some text in the same field as shown hereenter image description here

    So now how can i format my TextFormfield to restrict to type only number & to restrict pasting texts?

  • MohanKumar
    MohanKumar over 4 years
    This solution works, provided need to import import 'package:flutter/services.dart';