flutter

How to convert String to Int in Flutter

To convert a string to an integer in Flutter, you can use the int.parse() method or the int.tryParse() method.


Here's how you can do it:

Using int.parse() method

String strVal = '50';
int intVal = int.parse(strVal);

Output

50

In the example above, the int.parse() method takes a string stringValue and converts it to an integer intValue.

If the string cannot be parsed as an integer, it will throw a FormatException.


Using int.tryParse() method

String stringValue = '123';
int intValue = int.tryParse(stringValue);

if (intValue != null) {
  // Conversion successful
} else {
  // Conversion failed
}

The int.tryParse() method attempts to parse the string as an integer. If the conversion is successful, it returns the integer value. If the string cannot be parsed, it returns null. This allows you to handle the case when the conversion fails without throwing an exception.

It's important to note that both methods assume the string contains a valid integer representation. If the string contains non-numeric characters or is empty, the conversion will fail. Make sure to handle error cases appropriately, depending on your application's requirements.

Was this helpful?