DEV Community

ARUN
ARUN

Posted on

Age Calculator in Flutter

In this post I will share about Age Calculator in Flutter, this Calculator finds the Age in years, months, days, hours.

Let's get Started...

Overview

Get the Birth day of user by using datepicker, then find the difference between birthday and current day.

void _showPicker() {
    showDatePicker(
        context: context,
        firstDate:  DateTime(1900),
        initialDate:  DateTime(2023),
        lastDate: DateTime.now()).then((DateTime? dt) {
      selectedYear = dt?.year;
      selectedDay = dt?.day;
      selectedMon = dt?.month;
      calculateAge();
    });
  }
Enter fullscreen mode Exit fullscreen mode

this function is used to get the birthdate of user

age = (2023 - selectedYear).toDouble();
Enter fullscreen mode Exit fullscreen mode

this line is used to find the age in years.

DateTime date1 = DateTime(selectedYear, selectedMon, selectedDay);
      day = double.parse(date2.difference(date1).inDays.toString());
      month =  double.parse((date2.difference(date1).inDays / 30).floor().toString());
      hours = day*24.0;
Enter fullscreen mode Exit fullscreen mode

this line is used to find the age in months, days, hours, And these calculations are approximate values.

 @override
  void initState() {
    animationController =  AnimationController(
        vsync: this, duration:  Duration(milliseconds: 1500));
    animation = animationController;
    animation1 = animationController;
    animation2 = animationController;
    animation3 = animationController;
    super.initState();
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }
Enter fullscreen mode Exit fullscreen mode

And I use some Animations to visualize the results.

 animation =  Tween<double>(begin: animation.value, end: age).animate(
           CurvedAnimation(
              curve: Curves.fastOutSlowIn, parent: animationController));
      animation1 = Tween<double>(begin: animation.value, end: month).animate(
          CurvedAnimation(
              curve: Curves.fastOutSlowIn, parent: animationController));
      animation2 = Tween<double>(begin: animation.value, end: day).animate(
          CurvedAnimation(
              curve: Curves.fastOutSlowIn, parent: animationController));
      animation3 = Tween<double>(begin: animation.value, end: hours).animate(
          CurvedAnimation(
              curve: Curves.fastOutSlowIn, parent: animationController));
      animationController.forward(from: 0.0);
Enter fullscreen mode Exit fullscreen mode

These lines are used to show the result in animated view.

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:  AppBar(
        title:  Text("Age Calculator"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
             OutlinedButton(
              onPressed: _showPicker,
              child:  Text(selectedYear != null
                  ? selectedYear.toString()
                  : "Select your year of birth"),
            ),
             const Padding(
              padding: EdgeInsets.all(20.0),
            ),
             AnimatedBuilder(
              animation: animation,
              builder: (context, child) => Text(
                "Your Age in years ${animation.value.toStringAsFixed(0)}"
                    "\nYour Age in months ${animation1.value.toStringAsFixed(0)}"
                    "\nYour Age in days ${animation2.value.toStringAsFixed(0)}"
                    "\nYour Age in hours ${animation3.value.toStringAsFixed(0)}",
                style:  const TextStyle(
                    fontSize: 30.0,
                    fontWeight: FontWeight.bold,
                    fontStyle: FontStyle.italic),
              ),
            )
          ],
        ),
      ),
    );
  }

Enter fullscreen mode Exit fullscreen mode

This was the build method for our project.

And the following is the entire code for main.dart file


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

void main() => runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    theme:  ThemeData(primarySwatch: Colors.grey),
    home:  MyHomePage()));

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  double age = 0.0;
  double month = 0.0;
  double day = 0.0;
  double hours = 0.0;
  final date2 = DateTime.now();
  var selectedYear ; // for setting year
  var selectedDay ; // for setting date
  var selectedMon ; // for setting month
  late Animation animation; // this denoting age animation
  late Animation animation1; // this denoting month animation
  late Animation animation2; // this denoting date animation
  late Animation animation3; // this denoting hour animation
  late AnimationController animationController;

  @override
  void initState() {
    animationController =  AnimationController(
        vsync: this, duration:  Duration(milliseconds: 1500));
    animation = animationController;
    animation1 = animationController;
    animation2 = animationController;
    animation3 = animationController;
    super.initState();
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  void _showPicker() {
    showDatePicker(
        context: context,
        firstDate:  DateTime(1900),
        initialDate:  DateTime(2023),
        lastDate: DateTime.now()).then((DateTime? dt) {
      selectedYear = dt?.year;
      selectedDay = dt?.day;
      selectedMon = dt?.month;
      calculateAge();
    });
  }

  void calculateAge() {
    setState(() {
      age = (2023 - selectedYear).toDouble();
      DateTime date1 = DateTime(selectedYear, selectedMon, selectedDay);
      day = double.parse(date2.difference(date1).inDays.toString());
      month =  double.parse((date2.difference(date1).inDays / 30).floor().toString());
      hours = day*24.0;

      animation =  Tween<double>(begin: animation.value, end: age).animate(
           CurvedAnimation(
              curve: Curves.fastOutSlowIn, parent: animationController));
      animation1 = Tween<double>(begin: animation.value, end: month).animate(
          CurvedAnimation(
              curve: Curves.fastOutSlowIn, parent: animationController));
      animation2 = Tween<double>(begin: animation.value, end: day).animate(
          CurvedAnimation(
              curve: Curves.fastOutSlowIn, parent: animationController));
      animation3 = Tween<double>(begin: animation.value, end: hours).animate(
          CurvedAnimation(
              curve: Curves.fastOutSlowIn, parent: animationController));
      animationController.forward(from: 0.0);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:  AppBar(
        title:  Text("Age Calculator"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
             OutlinedButton(
              onPressed: _showPicker,
              child:  Text(selectedYear != null
                  ? selectedYear.toString()
                  : "Select your year of birth"),
            ),
             const Padding(
              padding: EdgeInsets.all(20.0),
            ),
             AnimatedBuilder(
              animation: animation,
              builder: (context, child) => Text(
                "Your Age in years ${animation.value.toStringAsFixed(0)}"
                    "\nYour Age in months ${animation1.value.toStringAsFixed(0)}"
                    "\nYour Age in days ${animation2.value.toStringAsFixed(0)}"
                    "\nYour Age in hours ${animation3.value.toStringAsFixed(0)}",
                style:  const TextStyle(
                    fontSize: 30.0,
                    fontWeight: FontWeight.bold,
                    fontStyle: FontStyle.italic),
              ),
            )
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Here i use one external package called Age_Calculator.

dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  age_calculator: ^1.0.0  # include here
Enter fullscreen mode Exit fullscreen mode

So you need to insert that in your pubspec.yaml file.


This was the final result.

Image description
You can also check this by here.

If you Like this, then put Likes and If you have any Queries then Comment your queries.

Thank you

Oldest comments (0)