flutter - 有人能告诉我为什么执行后会得到 'null' 输出吗?

标签 flutter dart

有人可以告诉我为什么我在 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/

相关文章:

dart - 如何将单选按钮设置为在 dart 聚合物组件中选中

flutter - Flutter GridView.count元素之间不必要的填充/空间

javascript - Flutter 和 Openlayers - 包括 Flutter 中的 js 库

android-studio - 在使用 Android Studio 启动期间失去与设备的连接

string - Dart:根据用户输入的字符串进行计算,包括数学运算符

名称和数字 Dart 的正则表达式

dart - @observable 是否必须在每个领域都使用?

flutter - 如何使用API​​和本地数据存储正确构建Flutter项目?

dart - Java byte[] 的 Dart 等价物是什么

flutter - TextOverflow.ellipsis 即使在扩展内部也不起作用