Home > Mobile >  Didn't calculate age and didn't display age when select birthday in flutter
Didn't calculate age and didn't display age when select birthday in flutter

Time:09-19

I built datepicker function. when the date selected then should calculate the age and should display date and age. The date display correctly but age not show.

code:- I called the calAge() method in the showdatepicker method

void showDatePicker() {
    DateTime mindate = new DateTime(now.year - 2, now.month, now.day);
    DateTime maxdate = new DateTime(now.year - 1, now.month, now.day);
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext builder) {
          return Container(
            height: MediaQuery.of(context).copyWith().size.height * 0.25,
            color: Colors.white,
            child: CupertinoDatePicker(
              mode: CupertinoDatePickerMode.date,
              initialDateTime: mindate,
              onDateTimeChanged: (value) {
                if (value != null && value != selectedDate)
                  setState(() {
                    selectedDate = value;
                    calAge();
                  });
              },
              maximumDate: maxdate,
              minimumDate: mindate,
            ),
          );
        });
  }

calAge() method

void calAge(DateTime selectedDate) {
    DateTime currentDate = DateTime.now();
    int age = currentDate.year - selectedDate.year;
    int month1 = currentDate.month;
    int month2 = selectedDate.month;
    if (month2 > month1) {
      age--;
    } else if (month1 == month2) {
      int day1 = currentDate.day;
      int day2 = selectedDate.day;
      if (day2 > day1) {
        age--;
      }
    }
    return age;
  }

print

 Text(selectedDate == null ? "" : "$selectedDate"),
  Text(selectedDate == null ? "" : "$age"),

CodePudding user response:

From the code you provided I would assume that in setState you should assign ˋage = calAge()ˋ

  • Related