Summary: In this tutorial, you’ll learn about the Dart int type and how to use it effectively.
Introduction to the Dart int type #
To represent integers like -1, 0, 1, 2, etc., you use the int type. In native platforms, the int type corresponds to a signed 64-bit integer.
Since Dart is also compiled to JavaScript, the int type maps to a 64-bit double-precision floating-point value on the web. This is because JavaScript only has floating-point numbers.
The following example declares a counter variable with the type int:
void main() {
int counter = 1;
print('counter: $counter');
}Code language: Dart (dart)Output:
counter: 1Code language: Dart (dart)Converting a string into an integer #
To convert a string into an integer, you use the int.parse(). For example:
void main() {
int qty = 5;
String amount = "100";
int total = qty * int.parse(amount);
print('Total: $total');
}Code language: Dart (dart)This example declares the amount variable as a string and converts it into an integer.
The int.parse() will raise an exception if it cannot convert the string into an integer. For example:
void main() {
String amountStr = "a100";
int amount = int.parse(amountStr);
print('Total: $amount');
}Code language: Dart (dart)Error:
FormatException: Invalid radix-10 number (at character 1)
a100
^Code language: Dart (dart)Summary #
- Use
inttype to represent integers. - Use
int.parse()to convert a string to an integer.