0

I have following statement in flutter. weight is the text from _weightController i.e. _weightController.text

int.parse(weight).toString().isNotEmpty && int.parse(weight) > 0

But in Dart 2.0 it is not working properly. For empty TextField, it is giving the error.

====== Exception caught by gesture ==============================
The following FormatException was thrown while handling a gesture: 
Invalid number (at character 1)

The code block is like this.

if (int.parse(weight).toString().isNotEmpty && int.parse(weight) > 0)
    return int.parse(weight) * multiplier;
  else
    print('Error');

2 Answers 2

1

As an alternative to the other answer, you can use the tryParse() method:

Like parse except that this function returns null where a similar call to parse would throw a FormatException, and the source must still not be null.

If you use this approach, you should check the return value for null:

String weight ="";
int number = int.tryParse(weight);
if (number !=null){
  print(number );
}
else
  print("error");

Don't forget to also check the variable for null with weight ? "" or with weight != null

Sign up to request clarification or add additional context in comments.

2 Comments

This worked for me. if (int.tryParse(weight) != null && int.tryParse(weight) > 0). Thanks. I also need to check for 0.
You mean weight ?? " ", Not single ?
1

Try this:

if (weight != null && weight.isNotEmpty) {
  return int.tryParse(weight) * multiplier;
} else {
  print("CoolTag: error");
  return -1;
}

2 Comments

This worked partially though. I had to also check for 0 which was giving error. I used int.tryParse(weight) > 0 and that worked for me.
Ok, but the accepted answer doesn't cover all the cases, which mine does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.