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
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. |
Return Type
int.tryParse() returns value of type int
.
✐ Examples
1 Parsing a string as an integer
In this example,
- We create a string variable
numStr1
with the value '42'. - We use the
tryParse
method to parsenumStr1
as an integer. - 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,
- We create a string variable
numStr2
with the value '-123'. - We use the
tryParse
method to parsenumStr2
as a signed integer. - 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,
- We create a string variable
numStr3
with the value '0x1F' which represents 31 in hexadecimal. - We use the
tryParse
method with a radix of 16 to parsenumStr3
as an integer in hexadecimal. - 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.