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(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Flutter TextField Number Input'),
        ),
        body: const MyStatefulWidget());
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  late TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
  }

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

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Center(
              child: Column(children: <Widget>[
                TextField(
                  controller: _controller,
                  keyboardType: TextInputType.number,
                  onSubmitted: (String value) {
                    debugPrint(value);
                  },
                ),
              ]),
            )));
  }
}

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.

Flutter TextField phone number input

I hope this Flutter tutorial is helpful for you.

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

Leave a Comment