How to show initial date in Cupertino Date Picker Field

3k Views Asked by At

This is a small form with a Cupertino date picker. I would like to show the initial date on the form. When the textfield is tapped it will show a datepicker and once a new date is chosen, it will show the new date

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


}

I've added date = newDateTime; to setState and Text(DateFormat.yMMMMd().format(newDateTime),) is still coming up as null. I'm think of using a ternary operator or is there a better way of doing it

1

There are 1 best solutions below

0
On BEST ANSWER

use the initState method to set the initial value for newDateTime

void initState() {
 super.initState();
 newDateTime = DateTime.now();
}