Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Term Entry] Dart Type Conversion .tryParse() #4572 #4586

Merged
merged 15 commits into from
May 1, 2024
Merged
47 changes: 47 additions & 0 deletions content/dart/concepts/type-conversion/terms/tryParse/tryParse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
Title: '.tryParse()'
Description: 'Parses a string and converts it to a specific data type'
Subjects:
- 'Computer Science'
- 'Developer Tools'
- 'Mobile Development'
- 'Web Development'
Tags:
- 'Dart'
- 'Data Types'
- 'Methods'
- 'Strings'
CatalogContent:
- 'learn-dart'
- 'paths/computer-science'
---

In Dart, **`.tryParse()`** is a static method available on several data types, such as `int` and `double`, for example. When called on a `string`, the `.tryParse()` method attempts to parse the string and returns a nullable value of the target data type if the parsing is successful. However, if parsing fails due to an invalid format in the string, the method returns `null`.

## Syntax

```pseudo
dataType.tryParse(stringToParse)
```
- `stringToParse` - Represents the `string` to be converted into the desired data type.
- `dataType` - Represents the data type to be converted to stringValue.
lou-pastorino marked this conversation as resolved.
Show resolved Hide resolved

## Example

```dart
void main() {
String input = '42';
int? parsedInt = int.tryParse(input);

if (parsedInt != null) {
print('Parsed integer: $parsedInt');
} else {
print('Failed to parse the string as an integer');
}
}
```
The above code will return the following output:

```dart
//Parsed integer: 42
```