Flutter: detect if a string can be converted to double

Viewed 332

I can do something like this:

double.parse(myString)

That's fine when I have "1.1" but if I have "1.1.1" it fails with Invalid double. Could I detect this somehow in advance?

I'd need this for input validations

3 Answers

Working with

 double.tryParse(myString)

As written above, use double.tryParse() or wrap double.parse() with try catch

An alternative, if you need to do input validation could be filter away "bad" input already when the user inputs the number.

You could change keyboard type and use input formatters on a TextField / TextFormFiel

TextField(
  decoration: new InputDecoration(labelText: "Enter your number"),
  keyboardType: TextInputType.number,
  inputFormatters: <TextInputFormatter> [
    FilteringTextInputFormatter.digitsOnly
  ], // Only numbers can be entered
),

You could write something like this

if(!myString.contains(<someregex>)) {
  double.parse(myString);
} 

Where the regex is validating that the string is a valid double, the value of doing this over using tryParse is that you can include your business rule validation alongside your datatype validation.

Related