I’m trying to make the user writing his birth to calculate the age in Flutter. But IDK why it is an error.
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;
});
},
),
3
Answers
Why is that a class? That needs to be a method:
And later using it like this:
While we are using null-safety, you need to
static int age = 0;
late
to promise will assign value before read time.static late int age;
?
and do a null check while it.static int? age;
I prefer making nullable data.
Find more about null-safety.
I suppose the error is this line:
You should be using the later version of dart/flutter. As you are declaring age non-nullable you either need to define it as nullable like that:
or give it some initial value like:
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: