为什么 `DateTime.add(const Duration(days: 1)` 添加 *秒* 而不是天?

发布于 2025-01-17 16:28:14 字数 2184 浏览 0 评论 0原文

我有一个 Text() 小部件,它将 DateTime 显示为 String。此 Text() 小部件用 GestureDetecture() 包装,其中 onTap 应将 DateTime 更新一 < em>day:

GestureDetector(
            child: File2(
              dateTime: date,
              key: Key(date.toString()),
            ),
            onTap: () {
              setState(() {
                // This is adding seconds not days
                date = date.add(const Duration(days: 1));
              });
            },
          ),

但是,虽然我正在这样做,但日期并没有更新一天:

date = date.add(const Duration(days: 1));

但是它会更新几秒钟。为什么1天还没更新?

我尝试过的: 使用Key()

代码:

file_1.dart

import 'package:flutter/material.dart';

import 'file_2.dart';

void main() {
  runApp(File1());
}

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

  @override
  State<File1> createState() => _File1State();
}

class _File1State extends State<File1> {
  @override
  Widget build(BuildContext context) {
    DateTime date = DateTime.now();

    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: GestureDetector(
            child: File2(
              dateTime: date,
              key: Key(date.toString()),
            ),
            onTap: () {
              setState(() {
                // This is adding seconds not days
                date = date.add(const Duration(days: 1));
              });
            },
          ),
        ),
      ),
    );
  }
}

file_2.dart

import 'package:flutter/material.dart';

class File2 extends StatelessWidget {
  DateTime dateTime;
  File2({Key? key, required this.dateTime}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Text(dateTime.toString());
  }
}
  • 如何更新单击 GestureDetector() 时,File2 中的 Text() 会增加 1 天吗?

  • 除了 setState() 之外,我还需要使用状态管理吗?

I have a Text() widget that displays a DateTime as a String. This Text() widget is wrapped with a GestureDetecture() where the onTap should update the DateTime by one day:

GestureDetector(
            child: File2(
              dateTime: date,
              key: Key(date.toString()),
            ),
            onTap: () {
              setState(() {
                // This is adding seconds not days
                date = date.add(const Duration(days: 1));
              });
            },
          ),

However, the date is not updating by one day although I'm doing:

date = date.add(const Duration(days: 1));

It is however updating by a few seconds. Why isn't it updating by 1 day?

What I tried:
Using a Key()

Code:

file_1.dart:

import 'package:flutter/material.dart';

import 'file_2.dart';

void main() {
  runApp(File1());
}

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

  @override
  State<File1> createState() => _File1State();
}

class _File1State extends State<File1> {
  @override
  Widget build(BuildContext context) {
    DateTime date = DateTime.now();

    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: GestureDetector(
            child: File2(
              dateTime: date,
              key: Key(date.toString()),
            ),
            onTap: () {
              setState(() {
                // This is adding seconds not days
                date = date.add(const Duration(days: 1));
              });
            },
          ),
        ),
      ),
    );
  }
}

file_2.dart:

import 'package:flutter/material.dart';

class File2 extends StatelessWidget {
  DateTime dateTime;
  File2({Key? key, required this.dateTime}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Text(dateTime.toString());
  }
}
  • How can I update the Text() in File2 by 1 day when clicking on the GestureDetector()?

  • Do I need to use a statemanagement other then setState()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深府石板幽径 2025-01-24 16:28:14

问题

发生此错误的原因很简单,因为您在构建方法的开头有这一行:DateTime date = DateTime.now();

这是代码中发生的工作流程:

  1. 在构建方法的开头将日期值设置为 DateTime.now()
  2. 当前日期值将呈现在您的 UI 中。
  3. 您触发该功能来更新您的日期。
  4. 将+1 天添加到日期。
  5. 重要提示:步骤 4 会触发小部件的重建,因此会再次执行步骤 1。

第 5 步的结果是,日期值仅更新了一会儿,但随后 DateTime.now() 在 UI 中呈现。

解决方案

在 State 类中而不是在构建方法中启动 date 值。这样,您的 date 值就不会被 Widget 重建覆盖:

class _File1State extends State<File1> {
  DateTime date = DateTime.now(); // <-- Initiate the value here
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: GestureDetector(
            child: File2(
              dateTime: date,
              key: Key(date.toString()),
            ),
            onTap: () {
              setState(() {
                // This is adding seconds not days
                date = date.add(const Duration(days: 1));
              });
            },
          ),
        ),
      ),
    );
  }
}

Problem

This error occurs simply because you have this line at the beginning of the build method: DateTime date = DateTime.now();.

This is the workflow of what is happening in your code:

  1. You set the date value to DateTime.now() at the beginning of the build method.
  2. This current date value is rendered in your UI.
  3. You trigger the function to update your date.
  4. +1 day is added to the date.
  5. IMPORTANT: Step 4 triggers the rebuild of your widget, hence Step 1 is executed again.

As a result of Step 5, the date value just gets updated for a moment, but then the DateTime.now() is rendered in UI.

Solution

Initiate the date value in your State class and not in the build method. This way, your date value won't be overwritten by the Widget rebuild:

class _File1State extends State<File1> {
  DateTime date = DateTime.now(); // <-- Initiate the value here
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: GestureDetector(
            child: File2(
              dateTime: date,
              key: Key(date.toString()),
            ),
            onTap: () {
              setState(() {
                // This is adding seconds not days
                date = date.add(const Duration(days: 1));
              });
            },
          ),
        ),
      ),
    );
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文