简体   繁体   中英

floating value formatting in TextFormField in Flutter

I want to add restriction on user input and force to type fractional value. But if I type .5 it causes invalid input exception but 0.5 works fine. But user may type .5 instead of 0.5. So is there any way to that. Here is my code:

inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp(r"[0-9.]")),
        TextInputFormatter.withFunction((oldValue, newValue) {
          try {
            final text = newValue.text;
            if (text.isNotEmpty) double.parse(text);
            return newValue;
          } catch (e) {}
          return oldValue;
        }),
      ],

That's because .5 is not parse-able to double you can add this line
if(text.startsWith('.')) text = '0$text';
before the if statement, so the code becomes:

try {
  String text = newValue.text;
  if (text.startsWith('.')) text = '0$text';
  if (text.isNotEmpty) double.parse(text);
  return newValue;
} catch (e) {}
return oldValue;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM