Flutter TextFormField – How to Create Digit-Only Input Fields

dartflutter

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?

Best Answer

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

Related Question