dart Flutter showDatePicker()每次单击返回时都会重置

d4so4syb  于 2023-05-04  发布在  Flutter
关注(0)|答案(3)|浏览(148)

我在我的Flutter应用程序中有一个部分,用户可以单击日期,它将从数据库中删除该日期的所有条目,问题是如果我进入日历并单击两个月前的日期,当我再次打开日历时,它将突出显示今天而不是我以前选择的日期,这意味着我必须一直滚动到我想要的日期,我如何解决这个问题
代码:

child: TextFormField(
        controller: _date,
        decoration: const InputDecoration(
            icon: Icon(Icons.calendar_today_rounded),
            labelText: "Select Date"),
        onTap: () async {
          DateTime? pickeddate = await showDatePicker(
              context: context,
              initialDate: DateTime.now(),
              firstDate: DateTime(2000),
              lastDate: DateTime(2101));

          if (pickeddate != null) {
            setState(() {
              _date.text = DateFormat('yyyy-MM-dd').format(pickeddate);
              currentDateSelected = _date.text;
              // updateDate(DateFormat('yyyy-MM-dd').format(pickeddate));
              _refreshSets();
              //print(DateFormat('yyyy-MM-dd').format(pickeddate));
            });
          }

          //Here i need to send off to the database that pickeddate
        },
      ),
mm9b1k5b

mm9b1k5b1#

下面的代码将texteditingcontroller中名为_date的文本解析为datetime格式,并将其用作选择器的初始日期。如果控制器的文本为空,则使用DateTime.now()

onTap: () async {
          DateTime? pickeddate = await showDatePicker(
              context: context,
              initialDate: _date.text.isEmpty ? DateTime.now() : DateTime.parse(_date.text),
              firstDate: DateTime(2000),
              lastDate: DateTime(2101));

          if (pickeddate != null) {
            setState(() {
              _date.text = DateFormat('yyyy-MM-dd').format(pickeddate);
              currentDateSelected = _date.text;
              // updateDate(DateFormat('yyyy-MM-dd').format(pickeddate));
              _refreshSets();
              //print(DateFormat('yyyy-MM-dd').format(pickeddate));
            });
          }

          //Here i need to send off to the database that pickeddate
        }
kb5ga3dv

kb5ga3dv2#

读取the doc中的showDatePicker构造函数

Future<DateTime?> showDatePicker(
{required BuildContext context,
required DateTime initialDate,
required DateTime firstDate,
required DateTime lastDate,
DateTime? currentDate,
...

currentDate表示当前日期(即今天)。此日期将在日网格中突出显示。如果为空,则DateTime.now将使用www.example.com()的日期。这导致了你的问题。

z9smfwbn

z9smfwbn3#

您有一个名为initialDate的属性,用于设置日期选择器的初始值。

DateTime selectedDate = DateTime.now();
...
 onTap: () async {
     DateTime? pickedDate = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2000),
        lastDate: DateTime(2101)
     );

     if (pickedDate != null) {
      setState(() {
        selectedDate = pickedDate;
        // Update selectedDate, so that now the new selected date acts
        // as the initial selected value
       });
     }
...

确保使用StatefulWidget并声明selectedDate变量,如下所示:

class _MyWidgetState extends State<MyWidget> {
   DateTime selectedDate = DateTime.now();
 ...
}

相关问题