Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict two dots in flutter?

Tags:

flutter

dart

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

like image 273
Jaya kumar Avatar asked Dec 30 '19 13:12

Jaya kumar


2 Answers

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()],
        ),
      ),
    );
  }
}
like image 124
Crazy Lazy Cat Avatar answered Oct 21 '22 00:10

Crazy Lazy Cat


With WhitelistingTextInputFormatter deprecated

TextField(
 keyboardType: TextInputType.numberWithOptions(decimal: true),
 inputFormatters: <TextInputFormatter>[
      FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d*')),
  ], // Only numbers can be entered
),
like image 21
Mathulan Avatar answered Oct 20 '22 22:10

Mathulan