I need to restrict when the user types 1.. like this. i'm using text input form field. I need input like 1.23 with decimal input text formatter
We can create our own TextInputFormatter
.
Check this
import 'package:flutter/services.dart';
class DecimalTextInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
final regEx = RegExp(r"^\d*\.?\d*");
String newString = regEx.stringMatch(newValue.text) ?? "";
return newString == newValue.text ? newValue : oldValue;
}
}
Usage:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FirstPage(),
debugShowCheckedModeBanner: false,
);
}
}
class FirstPage extends StatefulWidget {
@override
_FirstPageState createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextField(
inputFormatters: [DecimalTextInputFormatter()],
),
),
);
}
}
With WhitelistingTextInputFormatter deprecated
TextField(
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d*')),
], // Only numbers can be entered
),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With