I want only two digits after the decimal point in the flutter input.User can't add more than two digits after the decimal point.
I think MaskedTextController is unnecessary in your case, simply change int inputMaxValue to double inputMaxValue and possibly add . toStringAsFixed(3) to achieve 3 decimals after the dot. e.g. double inputMaxValue = 1.0; String inputIndexValue = "${inputMaxValue.
In Flutter, this can be done using TextEditingController . First, create a TextEditingController and set it as a controller property of your TextField widget. In this example, I have added an extra Button and Text widget which will show the added text when you click the “Show Text” button.
Steps to show numeric input keyboard in Flutter Step 1: Add TextField widget to your dart file. Step 2: Add keyboardType parameter and assign the TextInputType. number. Step 3: Add inputFormatters parameter and assign the [FilteringTextInputFormatter.
Here you go! Hope it helps :)
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'dart:math' as math; void main() { runApp(new MaterialApp(home: new MyApp())); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Flutter"), ), body: Form( child: ListView( children: <Widget>[ TextFormField( inputFormatters: [DecimalTextInputFormatter(decimalRange: 2)], keyboardType: TextInputType.numberWithOptions(decimal: true), ) ], ), ), ); } } class DecimalTextInputFormatter extends TextInputFormatter { DecimalTextInputFormatter({this.decimalRange}) : assert(decimalRange == null || decimalRange > 0); final int decimalRange; @override TextEditingValue formatEditUpdate( TextEditingValue oldValue, // unused. TextEditingValue newValue, ) { TextSelection newSelection = newValue.selection; String truncated = newValue.text; if (decimalRange != null) { String value = newValue.text; if (value.contains(".") && value.substring(value.indexOf(".") + 1).length > decimalRange) { truncated = oldValue.text; newSelection = oldValue.selection; } else if (value == ".") { truncated = "0."; newSelection = newValue.selection.copyWith( baseOffset: math.min(truncated.length, truncated.length + 1), extentOffset: math.min(truncated.length, truncated.length + 1), ); } return TextEditingValue( text: truncated, selection: newSelection, composing: TextRange.empty, ); } return newValue; } }
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