How to Make TextField Number only in Flutter

TextField is one of the most commonly used widgets in Flutter. It helps users to enter their text input. In this tutorial, let’s learn how to make the textfield number only by changing the keyboard type in Flutter.

The keyboardType property of TextField class helps you to change the keyboard type. The TextInputType.number makes your keyboard number only. See the code snippet given below.

TextField(
controller: myController,
keyboardType: TextInputType.number)

Following is the complete example.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Number only TextField',
      debugShowCheckedModeBanner: false,
      home: FlutterExample(),
    );
  }
}

class FlutterExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Number Type Text Input Example',
      home: MyInput(),
    );
  }
}

class MyInput extends StatefulWidget {
  @override
  _MyInputState createState() => _MyInputState();
}

class _MyInputState extends State<MyInput> {
  final myController = TextEditingController();

  @override
  void dispose() {
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Text Input Tutorial'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: TextField(
              controller: myController, keyboardType: TextInputType.number),
        ),
      ),
    );
  }
}

Following is the output.

Flutter TextField only number

The number-type keyboard is suitable for inputs such as numeric OTPs. If you want to use a TextField to enter the user phone number then you should prefer TextInputType.phone. Apart from number keys, It will have keys such as *, # etc.

I hope this Flutter tutorial is helpful for you.

1 thought on “How to Make TextField Number only in Flutter”

Leave a Comment

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