【问题标题】:how to calculate age in flutter?如何计算颤振的年龄?
【发布时间】:2022-07-08 12:51:53
【问题描述】:

flutter中如何计算年龄?

我想计算年龄 年月日和 还需要找到下一个生日... 这对我不起作用。 这是我的代码... 也可以尝试使用日期时间选择器,但月、日和年出现错误。

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)
                          ],
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

【问题讨论】:

  • 你的代码遇到了什么问题?
  • 输出年龄不正确..

标签: flutter dart flutter-layout


【解决方案1】:

导入'package:intl/intl.dart'; 导入'package:flutter_holo_date_picker/flutter_holo_date_picker.dart';

日期时间_selectedDate = DateTime.now().toLocal();

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

试试这个

    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}")

【讨论】:

    【解决方案2】:

    只需使用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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      • 2020-12-28
      • 2016-03-20
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多