Dart : Printing integer along with string
Asked Answered
B

4

20

Consider the below code.

void main() {
  int num = 5;
  print('The number is ' + num);
}

When I try to print the value for the variable num, I get the exception : The argument type 'int' can't be assigned to the parameter type 'String'.

How do I go about in printing num?

Barham answered 16/6, 2018 at 7:14 Comment(0)
A
41

In order to print the value of the int along with the String you need to use string interpolation:

void main() {
  int num = 5;
  print("The number is $num");
}
Acidulant answered 16/6, 2018 at 7:35 Comment(1)
This approach also worked for me in a RichText wdiget. Thanks!Damali
A
11

Just add toString() to your int. Similar to JS.

void main() {
  int num = 5;
  print('The number is ' + num.toString()); // The number is 5
}
Alienate answered 16/6, 2018 at 7:34 Comment(1)
This is not allowed, throughs a error in VSCode. Use method given by Pawel L.Alasteir
S
0
void main() {
int age = 10;
double location = 21.424567;
bool gender = true;
String name = "The EasyLearn Academy";

print(age); 
print(location);
print(gender); 
print(name); 

print("age $age"); 
print("location $location");
print("gender $gender"); 
print("name $name}"); 

print("age " + age.toString()); 
print("location " + location.toString());
print("gender " + gender.toString()); 
print("name " + name); 

}

Serenaserenade answered 19/12, 2021 at 12:1 Comment(0)
M
0

Could use ${} in order to concatenate with return of function:

print('$key|${favoriteBooksBox.get(key)}');
Maple answered 7/8, 2022 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.