A string can be cast to an integer using the int.parse()
method in Dart. The method takes a string as an argument and converts it into an integer.
The following code snippet demonstrates the usage of the int.parse
method:
import 'dart:convert'; void main() { var a = 10; // An integer var b = "20"; // A string var c = int.parse(b); print(a + c); }
The method also accepts strings that start with ; i.e., the format for hexadecimal numbers. Consider the code below which converts a hexadecimal string into an integer:
import 'dart:convert'; void main() { var a = "0x1E"; // Hexadecimal value for 30 var b = int.parse(a); print(b); }
The method will throw a
FormatException
if the input is invalid. The method won’t accept characters that are not radix-10 or hexadecimal (e.g., “abc”).
RELATED TAGS
View all Courses