我要求用户输入,它必须是字符串,而不是null。
用户可以以某种方式输入非字符串值或null吗?那么我会被迫验证它吗?或者我可以安全地跳过这个验证代码?(因为它是冗余的(
String? userInput = stdin.readLineSync();
if (userInput != null){
if (userInput.runtimeType == String){
print('Validated input');
} else{ // if is not a string
print('You did not entered a string');
}
print('You entered a null value'); // if null
}
首先,您通常不应该在生产代码中使用.runtimeType
。例如,在您的示例中,最好使用if (userInput is String)
来测试userInput
是否与String
类型兼容。不同的是,我们通常不关心确切的类型,而是关心某个东西是否与给定的类型兼容。
接下来,stdin.readLineSync()
被定义为返回String?
,这意味着类型系统强制它返回String
或null
。它不能返回例如数字。
所以你的if (userInput != null)
实际上已经足够了,因为如果是这样的话,我们知道userInput
必须是String
。
import 'dart:io';
void main() {
String? userInput = stdin.readLineSync();
if (userInput != null){
print('Validated input. Input must be a String.');
} else {
print('You entered a null value by closing the input stream!');
}
}
因为当userInput
可以变成null
时,如果用户正在关闭stdin输入流,就会发生这种情况。您可以在bash
(以及其他终端(中使用Ctrl+D键盘快捷键执行此操作。如果这样做,则userInput
将变为null
。