错误:参数类型“字符串?"不能分配给参数类型 'String',因为 'String?'可以为空,而 'String' 不是 [英] Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't

查看:39
本文介绍了错误:参数类型“字符串?"不能分配给参数类型 'String',因为 'String?'可以为空,而 'String' 不是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,我一直在尝试以下代码:

Good day, I have been trying the below code:

import 'dart:io';
main (){
print ("write your birth year:");
var birthyear = stdin.readLineSync();
var birthyearint = int.parse(birthyear);
var age = 2021-birthyearint;
print(age);
}

当我运行它时,我收到以下错误:

when I run it I receive the following error:

5:30:错误:参数类型字符串?"不能分配给参数类型 'String',因为 'String?'可以为空,而 'String' 不是.varbirthyearint = int.parse(birthyear);^

5:30: Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't. var birthyearint = int.parse(birthyear); ^

推荐答案

该错误是由 Dart 中的空安全特性引起的,参见 https://dart.dev/null-safety.

The error is caused by the null safety feature in Dart, see https://dart.dev/null-safety.

方法stdin.readLineSync()的结果是String?,即可能是String,也可能是null.方法 int.parse() 需要一个(非空)String.您应该检查用户是否提供了一些输入,然后您可以使用 birthyear! 断言该值是非空的.更好的是,您应该使用 int.tryParse() 来检查用户输入是否为有效整数,例如:

The result of method stdin.readLineSync() is String?, i.e. it may be a String, or it may be null. The method int.parse() requires a (non-null) String. You should check that the user gave some input, then you can assert that the value is non-null using birthyear!. Better still, you should use int.tryParse() to check that the user input is a valid integer, for example:

var birthyearint = int.tryParse(birthyear ?? "");
if (birthyearint == null) {
    print("bad year");
} else {
    var age = 2021-birthyearint;
    print(age);
}

这篇关于错误:参数类型“字符串?"不能分配给参数类型 'String',因为 'String?'可以为空,而 'String' 不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆