Dart int.tryParse()
Syntax & Examples


int.tryParse() static-method

The `tryParse` static method in Dart parses a string as an integer literal, possibly signed, and returns its value if successful.


Syntax of int.tryParse()

The syntax of int.tryParse() static-method is:

 int tryParse(String source, { int radix }) 

This tryParse() static-method of int parse source as a, possibly signed, integer literal and return its value.

Parameters

ParameterOptional/RequiredDescription
sourcerequiredThe string to parse as an integer.
radixoptionalThe base of the number system to use for parsing.

Return Type

int.tryParse() returns value of type int.



✐ Examples

1 Parsing a string as an integer

In this example,

  1. We create a string variable numStr1 with the value '42'.
  2. We use the tryParse method to parse numStr1 as an integer.
  3. We then print the parsed value to standard output.

Dart Program

void main() {
  String numStr1 = '42';
  int? parsed1 = int.tryParse(numStr1);
  print('Parsed value: $parsed1');
}

Output

Parsed value: 42

2 Parsing a signed integer from a string

In this example,

  1. We create a string variable numStr2 with the value '-123'.
  2. We use the tryParse method to parse numStr2 as a signed integer.
  3. We then print the parsed value to standard output.

Dart Program

void main() {
  String numStr2 = '-123';
  int? parsed2 = int.tryParse(numStr2);
  print('Parsed value: $parsed2');
}

Output

Parsed value: -123

3 Parsing a hexadecimal string as an integer

In this example,

  1. We create a string variable numStr3 with the value '0x1F' which represents 31 in hexadecimal.
  2. We use the tryParse method with a radix of 16 to parse numStr3 as an integer in hexadecimal.
  3. We then print the parsed value to standard output.

Dart Program

void main() {
  String numStr3 = '1F';
  int? parsed3 = int.tryParse(numStr3, radix: 16);
  print('Parsed value in hexadecimal: $parsed3');
}

Output

Parsed value in hexadecimal: 31

Summary

In this Dart tutorial, we learned about tryParse() static-method of int: the syntax and few working examples with output and detailed explanation for each example.