2

这是一个带有库比蒂诺日期选择器的小表格。我想在表格上显示初始日期。点击文本字段时,它将显示一个日期选择器,一旦选择了新日期,它将显示新日期

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

const double _kPickerSheetHeight = 216.0;

class AddCashPage extends StatefulWidget {
  @override
  _AddCashPageState createState() => _AddCashPageState();
}

class _AddCashPageState extends State<AddCashPage> {
  final _formKey = GlobalKey<FormState>();
  DateTime date = DateTime.now();
  DateTime newDateTime;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Form(
            key: _formKey,
            child: buildTextFormField(),
          ),
        ],
      ),
    );
  }

  Widget buildTextFormField() {
    return Column(
      children: <Widget>[
        GestureDetector(
          onTap: () {
            showCupertinoModalPopup<void>(
              context: context,
              builder: (BuildContext context) {
                return _buildBottomPicker(
                  CupertinoDatePicker(
                    mode: CupertinoDatePickerMode.date,
                    initialDateTime: date,
                    onDateTimeChanged: (DateTime addSelectedDate) {
                      setState(() {
                        this.newDateTime = addSelectedDate;
                           date = newDateTime;
                      });
                    },
                  ),
                );
              },
            );
          },
          child: _buildMenu(
            <Widget>[
              //Show initial date here
              Text(
                DateFormat.yMMMMd().format(newDateTime),
              ),
            ],
          ),
        ),
      ],
    );
  }


}

我已经添加 date = newDateTime;并且setState仍然Text(DateFormat.yMMMMd().format(newDateTime),)显示为空。我正在考虑使用三元运算符,或者有更好的方法吗

4

1 回答 1

2

使用该initState方法设置初始值newDateTime

void initState() {
 super.initState();
 newDateTime = DateTime.now();
}
于 2019-10-31T09:36:32.760 回答