The `tryParse` static method in Dart parses a string as an integer literal, possibly signed, and returns its value if successful.
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.
Parameter | Optional/Required | Description |
---|---|---|
source | required | The string to parse as an integer. |
radix | optional | The base of the number system to use for parsing. |
int.tryParse() returns value of type int
.
In this example,
numStr1
with the value '42'.tryParse
method to parse numStr1
as an integer.void main() {
String numStr1 = '42';
int? parsed1 = int.tryParse(numStr1);
print('Parsed value: $parsed1');
}
Parsed value: 42
In this example,
numStr2
with the value '-123'.tryParse
method to parse numStr2
as a signed integer.void main() {
String numStr2 = '-123';
int? parsed2 = int.tryParse(numStr2);
print('Parsed value: $parsed2');
}
Parsed value: -123
In this example,
numStr3
with the value '0x1F' which represents 31 in hexadecimal.tryParse
method with a radix of 16 to parse numStr3
as an integer in hexadecimal.void main() {
String numStr3 = '1F';
int? parsed3 = int.tryParse(numStr3, radix: 16);
print('Parsed value in hexadecimal: $parsed3');
}
Parsed value in hexadecimal: 31
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.