Dart:如何在字符串中输出整数?

20
考虑下面的代码。
void main() {
  int num = 5;
  print('The number is ' + num);
}

当我尝试打印变量num的值时,出现异常:参数类型'int'无法分配给参数类型'String'

我该如何打印num的值?

4个回答

41
为了将int的值与String一起打印出来,您需要使用字符串插值:
void main() {
  int num = 5;
  print("The number is $num");
}

这种方法在RichText小部件中对我也起作用了。谢谢! - Mike Dubs

11

只需将toString()添加到您的int中,与JS类似。

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

1
这是不允许的,在VSCode中会抛出错误。请使用Pawel L.提供的方法。 - SSG

0
可以使用 ${} 以便与函数的返回值连接:
print('$key|${favoriteBooksBox.get(key)}');

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); 

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接