[英]The non-nullable variable
I'm trying to make the user writing his birth to calculate the age in Flutter. But IDK why it is an error.我试图让用户写下他的出生来计算 Flutter 中的年龄。但 IDK 为什么这是一个错误。
import 'dart:io';
class AgeCalculator {
static int age;
AgeCalculator(int p) {
print('Enter your birth year: ');
int birthYear = p;
age = DateTime.now().year - birthYear;
print('your age is $age');
}
}
int str = 0;
ElevatedButton(
onPressed: () {
setState(() {
AgeCalculator(int.parse(myController.text));
str = AgeCalculator.age;
});
},
),
Why is that a class?为什么是 class? That needs to be a method:
这需要一个方法:
int calculateAge(int birthYear) {
return DateTime.now().year - birthYear;
}
And later using it like this:然后像这样使用它:
ElevatedButton(
onPressed: () {
setState(() {
str = calculateAge(int.parse(myController.text));
});
},
),
While we are using null-safety, you need to当我们使用空安全时,你需要
static int age = 0;
static int age = 0;
late
to promise will assign value before read time.late
到 promise 将在读取时间之前分配值。 static late int age;
?
?
and do a null check while it.static int? age;
I prefer making nullable data.我更喜欢制作可为空的数据。
Find more about null-safety .查找有关null-safety 的更多信息。
I suppose the error is this line:我想错误是这一行:
static int age;
You should be using the later version of dart/flutter .您应该使用更高版本的 dart/flutter 。 As you are declaring age non-nullable you either need to define it as nullable like that:
当您声明 age 不可为空时,您需要像这样将其定义为可空:
static int? age;
or give it some initial value like:或者给它一些初始值,例如:
static int age = 0;
The other way is making it late variable.另一种方法是使其成为后期变量。 But it has some danger .
但它有一定的危险性。 If you try to make some action on it without giving value, you get error in runtime :
如果您尝试在不提供值的情况下对其执行某些操作,则会在运行时出现错误:
static late int age;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.