Dart .tryParse()
Anonymous contributor
Published May 1, 2024
Contribute to Docs
In Dart, .tryParse() is a static method available on several data types, such as int and double. When called on a string, the .tryParse() method parses the string and converts it into the given data type if the parsing is successful. However, if parsing fails due to an invalid format in the string, the method returns null.
Syntax
dataType.tryParse(stringToParse)
stringToParse: Represents thestringto be converted into the desired data type.dataType: Represents the data type to be used to parsestringToParse.
Example
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 returns the following output:
Parsed integer: 42
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Dart on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours