Home > database >  how to calculate age in flutter?
how to calculate age in flutter?

Time:06-04

How to calculate age in flutter?

I wan to calulate age in year,month and days and also need to find next birthday... this is not working for me. this is my code... also try with date time picker but getting error for month,days,and year. enter code here

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyApp(),
    ),
  );
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  TextStyle txt = const TextStyle(fontSize: 20, color: Colors.white);
  String DD = "00", MM = "00", YYYY = "0000";

  int presentYear = 00;
  int presentMonth = 00;
  int presentDay = 00;

  int nMonth = 0;
  int nDay = 0;

  final datecontroller = TextEditingController();
  final monthcontroller = TextEditingController();
  final yearcontroller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    double h = MediaQuery.of(context).size.height;
    double w = MediaQuery.of(context).size.width;
    DateTime currentDate = DateTime.now();
    String formattedDate = DateFormat('d MMM, y').format(currentDate);

    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text(
          "Age Calculator",
          style: TextStyle(
            fontWeight: FontWeight.w300,
            fontSize: 25,
            color: Colors.white,
          ),
        ),
        centerTitle: true,
        backgroundColor: const Color(0xff202A43),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            Expanded(
              flex: 1,
              child: Column(
                children: [
                  const Align(
                    alignment: Alignment.topLeft,
                    child: Text("Today's Date",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w600,
                          letterSpacing: 1,
                          color: Color(0xff000000),
                        )),
                  ),
                  const Padding(padding: EdgeInsets.only(top: 5)),
                  Container(
                    alignment: Alignment.centerLeft,
                    height: h / 13,
                    width: w,
                    decoration: BoxDecoration(
                        border: Border.all(width: 1, color: Colors.grey),
                        borderRadius: BorderRadius.circular(8)),
                    padding: const EdgeInsets.only(left: 20),
                    child: Text(
                      formattedDate,
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Color(0xff1C003E),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            const Padding(padding: EdgeInsets.only(bottom: 15)),
            Expanded(
              flex: 1,
              child: Column(
                children: [
                  const Align(
                    alignment: Alignment.topLeft,
                    child: Text("Date of Birth",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w600,
                          letterSpacing: 1,
                          color: Color(0xff000000),
                        )),
                  ),
                  const Padding(padding: EdgeInsets.only(top: 0)),
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: Container(
                          alignment: Alignment.centerLeft,
                          height: h / 13,
                          width: w / 3,
                          child: Align(
                            child: TextField(
                              inputFormatters: <TextInputFormatter>[
                                FilteringTextInputFormatter.digitsOnly
                              ],
                              keyboardType: TextInputType.number,
                              controller: datecontroller,
                              onChanged: (d) {
                                DD = d;
                                print("$DD");
                              },
                              textAlign: TextAlign.center,
                              decoration: const InputDecoration(
                                  hintText: "DD", border: OutlineInputBorder()),
                            ),
                          ),
                        ),
                      ),
                      const Padding(padding: EdgeInsets.only(right: 5)),
                      Expanded(
                        flex: 1,
                        child: Container(
                          alignment: Alignment.centerLeft,
                          height: h / 13,
                          width: w / 3,
                          child: Align(
                            child: TextField(
                              inputFormatters: <TextInputFormatter>[
                                FilteringTextInputFormatter.digitsOnly
                              ],
                              keyboardType: TextInputType.number,
                              controller: monthcontroller,
                              onChanged: (m) {
                                MM = m;
                                print("$MM");
                              },
                              textAlign: TextAlign.center,
                              decoration: const InputDecoration(
                                  hintText: "MM", border: OutlineInputBorder()),
                            ),
                          ),
                        ),
                      ),
                      const Padding(padding: EdgeInsets.only(right: 5)),
                      Expanded(
                        flex: 1,
                        child: Container(
                          alignment: Alignment.centerLeft,
                          height: h / 13,
                          width: w / 3,
                          child: Align(
                            child: TextField(
                              keyboardType: TextInputType.number,
                              inputFormatters: <TextInputFormatter>[
                                FilteringTextInputFormatter.digitsOnly
                              ],
                              controller: yearcontroller,
                              onChanged: (y) {
                                YYYY = y;
                                print("$YYYY");
                              },
                              textAlign: TextAlign.center,
                              decoration: const InputDecoration(
                                  hintText: "YYYY",
                                  border: OutlineInputBorder()),
                            ),
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
            const Padding(padding: EdgeInsets.only(bottom: 35)),
            Expanded(
              flex: 1,
              child: Column(
                children: [
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: InkWell(
                          onTap: () {
                            setState(() {
                              datecontroller.clear();
                              monthcontroller.clear();
                              yearcontroller.clear();
                            });
                          },
                          child: Container(
                            alignment: Alignment.centerLeft,
                            height: h / 16,
                            width: w / 2,
                            decoration: BoxDecoration(
                                border: Border.all(
                                    width: 1, color: const Color(0xff13547A)),
                                borderRadius: BorderRadius.circular(8)),
                            child: const Align(
                                child: Text(
                              "Clear",
                              style: TextStyle(
                                  fontSize: 25, fontWeight: FontWeight.bold),
                            )),
                          ),
                        ),
                      ),
                      const Padding(padding: EdgeInsets.only(right: 5)),
                      Expanded(
                        flex: 1,
                        child: InkWell(
                          onTap: () {
                            setState(() {
                              presentMonth = currentDate.month - int.parse(MM);
                              presentYear = (currentDate.month < int.parse(MM))
                                  ? (currentDate.year - int.parse(YYYY)) - 1
                                  : (currentDate.year - int.parse(YYYY));
                              presentDay = 30 - int.parse(DD);

                              nMonth = int.parse(MM) - currentDate.month;
                              nDay = currentDate.day - int.parse(DD);
                            });
                          },
                          child: Container(
                            alignment: Alignment.centerLeft,
                            height: h / 16,
                            width: w / 2,
                            decoration: BoxDecoration(
                                color: const Color(0xff13547A),
                                borderRadius: BorderRadius.circular(8)),
                            child: const Align(
                                child: Text(
                              "Calculate",
                              style: TextStyle(
                                fontSize: 25,
                                color: Colors.white,
                              ),
                            )),
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
            Expanded(
              flex: 2,
              child: Column(
                children: [
                  const Align(
                    alignment: Alignment.topLeft,
                    child: Text("Present Age",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w600,
                          letterSpacing: 1,
                          color: Color(0xff000000),
                        )),
                  ),
                  const Padding(padding: EdgeInsets.only(top: 5)),
                  Container(
                    height: h / 6,
                    width: w,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        gradient: const LinearGradient(
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                            colors: [Color(0xff13547A), Color(0xff203A43)])),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text("$presentYear", style: txt),
                            Text("Year", style: txt)
                          ],
                        ),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text("$presentMonth", style: txt),
                            Text("MM", style: txt)
                          ],
                        ),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text("$presentDay", style: txt),
                            Text("DD", style: txt)
                          ],
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
            const Padding(padding: EdgeInsets.only(bottom: 10)),
            Expanded(
              flex: 2,
              child: Column(
                children: [
                  const Align(
                    alignment: Alignment.topLeft,
                    child: Text("Next Birthday",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w600,
                          letterSpacing: 1,
                          color: Color(0xff000000),
                        )),
                  ),
                  const Padding(padding: EdgeInsets.only(top: 5)),
                  Container(
                    height: h / 6,
                    width: w,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8),
                        gradient: const LinearGradient(
                            begin: Alignment.bottomLeft,
                            end: Alignment.topRight,
                            colors: [Color(0xff6BBED9), Color(0xff006ACb)])),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text("$nMonth", style: txt),
                            Text("MM", style: txt)
                          ],
                        ),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text("$nDay", style: txt),
                            Text("DD", style: txt)
                          ],
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

CodePudding user response:

import 'package:intl/intl.dart'; import 'package:flutter_holo_date_picker/flutter_holo_date_picker.dart';

DateTime _selectedDate = DateTime.now().toLocal();

var myFormat = DateFormat('d-MM-yyyy');

try this

    DatePickerWidget(
              looping: false,
              firstDate: DateTime(1950),
              //DateTime(1960),
              lastDate: DateTime(2050),
             initialDate: DateTime.now(),// DateTime(1994),
              dateFormat:"dd/MMMM/yyyy",
              // "MM-dd(E)",
              locale: DatePicker.localeFromString('en'),
              onChange: (DateTime newDate, _) {
                setState(() {
                  _selectedDate = newDate;

                });
                print(DateTime.now().year-_selectedDate.year);
              },
              pickerTheme: const DateTimePickerTheme(
                itemTextStyle:
                  TextStyle(color: Colors.black, fontSize: 19),
                dividerColor: Colors.black,
              ),
            ),

        Text("${DateTime.now().year-_selectedDate.year}")

CodePudding user response:

Just use age_calculator: ^1.0.0

import 'package:age_calculator/age_calculator.dart';

void main() {
  DateTime birthday = DateTime(1997, 3, 5);

  DateDuration duration;

  // Find out your age as of today's date 2021-03-08
  duration = AgeCalculator.age(birthday);
  print('Your age is $duration'); // Your age is Years: 24, Months: 0, Days: 3

  //Find out your age on any given date
  duration = AgeCalculator.age(birthday, today: DateTime(2030, 5, 1));
  print('Your age is $duration'); // Your age is Years: 33, Months: 1, Days: 26

  // Find out when your next birthday will be at 2021-03-08
  duration = AgeCalculator.timeToNextBirthday(birthday);
  print('You next birthday will be in $duration');
  // You next birthday will be in Years: 0, Months: 11, Days: 25

  // Find out when your next birthday will be on any given date
  duration = AgeCalculator.timeToNextBirthday(birthday,
      fromDate: DateTime(2021, 3, 2));
  print('You next birthday will be in $duration');
  // You next birthday will be in Years: 0, Months: 0, Days: 3

  // Find out the difference between two dates
  duration = AgeCalculator.dateDifference(
    fromDate: DateTime(2021, 1, 2),
    toDate: DateTime(2025, 5, 2),
  );
  print('The difference is $duration');
  // You next birthday will be in Years: 4, Months: 4, Days: 0

  // Add time to any date
  DateTime date = AgeCalculator.add(
      date: DateTime(2021, 1, 2),
      duration: DateDuration(years: 5, months: 2, days: 1));
  print(date);
  // 2026-03-03 00:00:00.000
}
  • Related