Press "Enter" to skip to content

Solved: Digits Only Input Keyboard in Flutter – Only Numbers on Text Field

Is it possible to create a Numeric input TextField or TextFormField on Flutter?

Normally in both android and iOS, keyboard contain numbers, alphabets and other symbols. But in some cases like entering the age, we need to limit the type of entry as Digits only using keyboard layout, so user cannot type anything except numbers.  

In Android studio, you can revoke a numeric only keyboard, but in flutter, you cannot revoke such a ‘digits only keyboard’ in all devices (may be on iOS) but you can limit the entry to number only.

How it possible?

We need two components:

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,

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.

inputFormatters: <TextInputFormatter>[
                    WhitelistingTextInputFormatter.digitsOnly
                   ],

Full App Example Code:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Add Two Numbers';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: BuildBody(),
      ),
    );
  }
}
class BuildBody extends StatefulWidget {
  @override
  _BuildBodyState createState() => _BuildBodyState();
}

class _BuildBodyState extends State<BuildBody> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Text(" Type a number: "),
              new Flexible(
                child: new TextField(
                  keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                    WhitelistingTextInputFormatter.digitsOnly
                   ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

Sample Outputs:

Numeric Input keyboard on flutter apps
Digits Only Keyboard inputs on Flutter Apps

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *