skip to Main Content

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


  1. Why is that a 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));
        });
      },
    ),
    
    Login or Signup to reply.
  2. While we are using null-safety, you need to

    • assign value, static int age = 0;
    • or using late to promise will assign value before read time. static late int age;
    • or make it nullable with ? and do a null check while it. static int? age;

    I prefer making nullable data.

    Find more about null-safety.

    Login or Signup to reply.
  3. I suppose the error is this line:

      static int age;
    

    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:

      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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search