错误:参数类型为“字符串?"无法分配给参数类型“字符串",因为“字符串?"为可空值,而'String'不是

编程入门 行业动态 更新时间:2024-10-22 23:43:18
本文介绍了错误:参数类型为“字符串?"无法分配给参数类型“字符串",因为“字符串?"为可空值,而'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安全功能引起的,请参见 dart.dev/null-safety .

The error is caused by the null safety feature in Dart, see 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'不是

本文发布于:2023-10-29 03:55:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538650.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   参数   类型   错误   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!