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

查看:421
本文介绍了错误:参数类型为“字符串?"无法分配给参数类型“字符串",因为“字符串?"为可空值,而'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:错误:参数类型为字符串?"无法分配给参数类型字符串",因为字符串?"是可以为空的,而字符串"不是.var birthyearint = 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中的null安全功能引起的,请参见

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

方法 stdin.readLineSync()的结果为 String?,即它可以是 String ,也可以是.方法 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'不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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