Amani
Amani

Reputation: 18173

Date picker field does not respond in Flutter TextFormField

I have the below Dart code in a Flutter web app with a TextFormField that is suppose to show a date picker for the respondent to pick the date. The code compiles fine, but then upon clicking the date field from a browser when the app is running nothing happen, no date picker is shown. What am I missing or doing wrong?

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class DateQuestionCard extends StatelessWidget {
  DateQuestionCard({
    @required this.question,
    @required this.validationInfo,
    this.isRequired = false,
    this.inputFormatters,
    this.keyboardType,
    this.controller,
  });

  String? question = '';
  String? validationInfo = '';
  bool isRequired;
  List<TextInputFormatter>? inputFormatters;
  TextInputType? keyboardType;
  TextEditingController? controller;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(25),
      margin: EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(question!),
          SizedBox(
            height: 10,
          ),

          // The date picker
          TextFormField(
            controller: controller,
            decoration: InputDecoration(
              hintText: "Insert your date of birth",
              hintStyle: TextStyle(
                color: Colors.grey[400],
                fontStyle: FontStyle.italic,
              ),
            ),
            onTap: () async {
              DateTime? date = DateTime(1980);
              FocusScope.of(context).requestFocus(FocusNode());

              date = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: DateTime(1980),
                lastDate: DateTime(2005),
              );

              controller!.text = date!.toIso8601String();
            },
            validator: (value) {
              if ((value == null || value.isEmpty) && isRequired) {
                return validationInfo;
              }

              return null;
            },
          ),
        ],
      ),
    );
  }
}

Upvotes: 0

Views: 441

Answers (1)

sniggl
sniggl

Reputation: 26

your error is quite simple:

initialDate: DateTime.now(),
firstDate: DateTime(1980),
lastDate: DateTime(2005),

Your date range is 1980-2005. But since we have 2021 your initialDate can't be DateTime.now.

Solution: Give a valid initialDate or change your lastDate to >= DateTime.now

Cheers, sniggl

Upvotes: 1

Related Questions