用户输入是否可能为非String类型或null?是否需编写验证代码?
关于Dart终端输入的类型与验证问题
核心结论
- 用户会不会输入非String类型?不可能
Dart里stdin.readLineSync()的返回类型是String?,只要返回值非null,就必然是String类型,不存在其他类型的可能。你代码里判断userInput.runtimeType == String完全是冗余操作,没必要写。 - 用户会不会输入null?有可能
当用户通过终端关闭输入流(比如Unix下按Ctrl+D,Windows下按Ctrl+Z)时,readLineSync()会返回null;输入过程出现异常时也可能返回null,但这种场景较少见。 - 是否需要验证?只需要验证null,无需验证类型
修正后的代码示例
import 'dart:io'; void main() { String? userInput = stdin.readLineSync(); if (userInput != null) { // 此处userInput必然为String类型,无需额外类型判断 print('Validated input'); } else { print('You entered a null value'); } }
补充:验证非空字符串
如果你的需求是输入必须为非null且非空的字符串,可以增加空串判断:
import 'dart:io'; void main() { String? userInput = stdin.readLineSync(); if (userInput != null && userInput.isNotEmpty) { print('Validated non-empty input'); } else if (userInput == null) { print('You entered a null value'); } else { print('You entered an empty string'); } }
内容的提问来源于stack exchange,提问作者Nicolás Ferrada
相关产品推荐
相关产品推荐

