Creating Number Input Field in Flutter

In this article, you will see how to create a number input field that takes only numbers from the keyboard. When you have taken user input only the numbers of mobile application. A sample video example is below.

1. The keyboard type should be a number. If you set the number field then write the below code.

 keyboardType: TextInputType.number

2. set the input formats to digit only and write the below code. 

 inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(r'[0-9]'),
),
]

Here is the step by step Implementation process:

Step 1:Create a new project in the Flutter project or you can use an already created Flutter project. 



Step 2: In important methods and then call the runApp method in while running the project.
 void main() {
runApp(HomeScreen());
}

class HomeScreen extends StatefulWidget {
@override
_State createState() => _State();
}

class _State extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
//code here
}
}
Step 3: Final code of example 
 import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/services.dart';
void main() {
runApp(HomeScreen());
}

class HomeScreen extends StatefulWidget {
@override
_State createState() => _State();
}

class _State extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter TextField Example'),
),
body: Padding(
padding: EdgeInsets.all(15),
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(15),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'User Number',
hintText: 'Enter Your Number',

),
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(r'[0-9]'),
),
]
),
),


],
)
)
);
}
}
Step 5: Output of above example


Happy coding!

365Bloggy May 28, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive