有人可以告诉我为什么我在 Result-1 末尾得到“null”输出吗?
#当我从主函数返回“Exercise1()”时,不会出现空值。 #但是我很困惑,想知道是什么导致结果中出现空值。
main.dart
import 'exercises/exercise1.dart';
void main() {
// return Exercise1();
print(Exercise1());
}
练习1.dart
import 'dart:io';
Exercise1() {
stdout.write("What is your name? \n");
String? name = stdin.readLineSync();
stdout.write("Hi $name, What is your age? \n");
int? age = int.parse(stdin.readLineSync().toString());
int? yearsLeftFor100 = 100 - age;
print("Hello $name, your age is $age");
print("Hi $name, you will attain 100 years in another $yearsLeftFor100 years.");
}
Result-1:使用 print(Exercise1()) 语句运行;
$ dart run main.dart
What is your name?
John Doe
Hi John Doe, What is your age?
31
Hello John Doe, your age is 31
Hi John Doe, you will attain 100 years in another 69 years.
null
结果2:使用returnExercise1()语句运行;
$ dart run main.dart
What is your name?
John Doe
Hi John Doe, What is your age?
31
Hello John Doe, your age is 31
Hi John Doe, you will attain 100 years in another 69 years.
最佳答案
由于您没有声明Exercise1()的返回类型,因此它的返回类型是动态。
由于您的方法中没有 return 语句,因此返回类型为 void。这意味着它不会返回任何内容。
因此,当您打印其调用的返回值时,您会看到 null。
关于flutter - 有人能告诉我为什么执行后会得到 'null' 输出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71634516/