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();
});
}

this function is used to get the birthdate of user

Enter fullscreen mode Exit fullscreen mode

age = (2023 - selectedYear).toDouble();

this line is used to find the age in years.

Enter fullscreen mode Exit fullscreen mode

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;

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

Enter fullscreen mode Exit fullscreen mode

@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();
}

And I use some Animations to visualize the results.

Enter fullscreen mode Exit fullscreen mode

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

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

Enter fullscreen mode Exit fullscreen mode

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Age Calculator"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
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),
),
)
],
),
),
);
}


This was the build method for our project.

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

Enter fullscreen mode Exit fullscreen mode

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 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);
});
Enter fullscreen mode Exit fullscreen mode

}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Age Calculator"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
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),
),
)
],
),
),
);
}
}


Here i use one external package called `Age_Calculator`.

Enter fullscreen mode Exit fullscreen mode

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

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

---

This was the final result.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0k2m61ygyd6azagppbsy.png)
You can also check this by [here](https://arun.engineer/Age_Calculator/).

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

Thank you 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)