Dart程序中return语句为何未呈现预期效果?
问题解答:Dart函数return语句未生效的原因
先看你的代码:
String fun(int age, String name) { print("hi"); return 'My name is $name and i am $age'; } void main() { print("Hello! Good Morning good people."); fun(21,"Jasraj"); }
输出结果:
Hello! Good Morning good people.
hi
原因分析
你的fun函数确实正确返回了字符串,但你只是调用了函数,却没有对返回值做任何处理——既没有用变量接收它,也没有直接打印输出。返回值虽然存在,但不会自动显示在控制台中。
解决方法
如果想要看到return的内容,只需在调用函数时处理返回值,两种常见方式:
方式1:直接打印函数返回值
void main() { print("Hello! Good Morning good people."); print(fun(21,"Jasraj")); // 打印函数返回的字符串 }
方式2:用变量接收后打印
void main() { print("Hello! Good Morning good people."); String result = fun(21,"Jasraj"); print(result); }
修改后运行,输出会变为:
Hello! Good Morning good people.
hi
My name is Jasraj and i am 21
内容的提问来源于stack exchange,提问作者Jasraj Pannu
相关产品推荐
相关产品推荐

