a shot of dev knowledge

Related tags

How to cast a string to an integer in Dart

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.

svg viewer

Code

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 0x0x; 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

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring