Trusted answers to developer questions

How to cast a string to an integer in Dart

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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

dart
string
int
casting
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?