Home > Net >  How to calculate age from datepicker using flutter?
How to calculate age from datepicker using flutter?

Time:11-01

In my code I used datepicker to selcte birthday .In date picker has a rang.And when the user select birthday and close the app and reopen later then also display that selected birthday.For that I used sharedprefernces , I want calculate age from birthday when the user select birthday then should automatically calculate age.

Image of UI

enter image description here

package

enter image description here

code

import 'package:age_calculator/age_calculator.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class BirthdayScreen extends StatefulWidget {
  const BirthdayScreen({Key? key}) : super(key: key);

  @override
  State<BirthdayScreen> createState() => _BirthdayScreenState();
}

class _BirthdayScreenState extends State<BirthdayScreen> {
  // 1st dropdown button
  @override
  void initState() {
    super.initState();
    dropdownValueBirthday = birthday.first;
    checkValueBirthday();
  }

  //date picker
  DateTime? selectedDate;
  DateTime now = new DateTime.now();
  void showDatePicker() {
    DateTime mindate = DateTime(now.year - 2, now.month, now.day - 29);
    DateTime maxdate = 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 != selectedDate) {
                  setState(() {
                    selectedDate = value;
                    dropdownValueBirthday =
                        '${selectedDate?.year}/${selectedDate?.month}/${selectedDate?.day} ';
                    calAge();
                  });
                }
              },
              maximumDate: maxdate,
              minimumDate: mindate,
            ),
          );
        });
  }

  String? dropdownValueBirthday;
  List<String> birthday = [
    'Birthday',
  ];

  //IF "dropdownValueMembers" is empty pass "which" word as a initial value if al ready selected then pass the shared preference value
  checkValueBirthday() {
    _getDataBirthday();
  }

  _saveDataBirthday(String dropdownValueBirthdayShared) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("dataBirthday", dropdownValueBirthdayShared);
  }

  _getDataBirthday() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    dropdownValueBirthday =
        sharedPreferences.getString("dataBirthday") ?? birthday.first;
    setState(() {});
  }

  String age = "";
  DateDuration? duration;
  getAge(DateTime fromDate) =>
      DateTime.now().difference(fromDate).inDays ~/ 365;

  void calAge() {
    // DateTime birthday = DateTime.parse(dropdownValueBirthday!);
    //
    // setState(() {
    //   duration = AgeCalculator.age(birthday);
    // });

    DateTime? birt; // DateTime(1990);
    if (birt != null) {
      print('age from birt: ${getAge(birt)}');
    } else {
      print('birt is null');
    }
  }

  @override
  Widget build(BuildContext context) {
    print(duration);
    print(dropdownValueBirthday);
    return Scaffold(
      body: Container(
        child: Column(
          children: [
            Center(
              child: Padding(
                padding: const EdgeInsets.only(left: 15, top: 100),
                child: Row(
                  children: <Widget>[
                    const Icon(
                      Icons.brightness_1,
                      color: Colors.black,
                      size: 10,
                    ),
                    const Padding(
                      padding: EdgeInsets.only(left: 15.0),
                      child: Text("birthday",
                          style: TextStyle(
                            fontSize: 16.0,
                          )),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 25.0),
                      child: SizedBox(
                        width: 110.0,
                        height: 25.0,
                        child: DecoratedBox(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(12),
                            color: Colors.white,
                          ),
                          child: Center(
                            child: Text(
                              selectedDate == null
                                  ? (dropdownValueBirthday ?? birthday.first)
                                  : '${selectedDate?.year}/${selectedDate?.month}/${selectedDate?.day} ',
                              style: const TextStyle(
                                  fontSize: 16, fontWeight: FontWeight.w500),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 15.0, top: 30.0),
                      child: SizedBox(
                        width: 88.0,
                        height: 25.0,
                        child: MaterialButton(
                          onPressed: showDatePicker,
                          shape: const StadiumBorder(),
                          color: Colors.blue,
                          child: const Text(
                            'select',
                            style: TextStyle(color: Colors.white, fontSize: 12),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(
                bottom: 0.0,
              ),
              child: SizedBox(
                width: 160.0,
                height: 35.0,
                child: ElevatedButton(
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(18.0),
                          side: const BorderSide(
                            color: Colors.blueAccent,
                          ),
                        ),
                      ),
                    ),
                    onPressed: () {
                      _saveDataBirthday(dropdownValueBirthday!);
                      // _saveDataAgree(isChecked!);
                    },
                    child: const Text('next')),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

now display this

enter image description here

CodePudding user response:

if (value != selectedDate) {
              setState(() {
                selectedDate = value;
                if(value != null){
                  birt = DateTime.now().difference(value).inDays ~/ 365;
                }
                dropdownValueBirthday =
                    '${selectedDate?.year}/${selectedDate?.month}/${selectedDate?.day} ';
                calAge();
              });

and decalre the birt at the top Datetime? birt;

void calAge() {
// DateTime birthday = DateTime.parse(dropdownValueBirthday!);
//
// setState(() {
//   duration = AgeCalculator.age(birthday);
// });

if (birt != null) {
  print('age from birt: ${getAge(birt)}');
} else {
  print('birt is null');
}

}

CodePudding user response:

I haven't counted leap years but for me is acceptable.

/*
getAge(DateTime fromDate) => DateTime.now().difference(fromDate).inDays ~/ 365;

void main() {
  DateTime? birt; // DateTime(1996); 
  if(birt != null){
    print('age from birt: ${getAge(birt)}');
  }else{
    print('birt is null');
  }
}
*/
getAge(DateTime? fromDate) => fromDate != null ? DateTime.now().difference(fromDate).inDays ~/ 365 : null;

void main() {
  print('getAge result: ${getAge(null)}'); // getAge result: null
  print('getAge result: ${getAge(DateTime(1990))}'); // getAge result: 32
  print('getAge result: ${getAge(DateTime(2020))}'); // getAge result: 2
}
  • Related