Home > Enterprise >  how to restrict choose date in datepicker flutter
how to restrict choose date in datepicker flutter

Time:06-22

I have two TextFormField startdate and enddate that takes date as a input from date picker. i want to restrict that user can not allow to select enddate before selected startdate.Be able to select from after selected startdate.how can i manage that. Here is my cample code

TextFormField(
              controller: startDate,
              readOnly: true,
              validator: (startDate){
                if(startDate==null|| startDate.isEmpty){
                  return "Please Input Start Date";
                }else return null;
              },
              onTap: () async{
                DateTime? startPickedDate = await showDatePicker(
                    context: context,
                    initialDate: DateTime.now(),
                    firstDate:DateTime.now(),
                    lastDate: DateTime(2100)
                );
                if(startPickedDate!= null){
                  String formattedDate = DateFormat('dd-MM-yyyy').format(startPickedDate);
                  setState(() {
                    startDate.text = formattedDate; //set output date to TextField value.
                  });
                }
              },
            )

            TextFormField(
              controller: endDate,
              readOnly: true,
              
              validator: (endDate){
                if(endDate==null || endDate.isEmpty){
                  return "Please Input End Date";
                }else return null;
              },
              onTap: () async{
                DateTime? endPickedDate = await showDatePicker(
                  context: context,
                  initialDate: DateTime.now(),
                  firstDate:  DateTime.now(),
                  lastDate: DateTime(2100),
                );
                if(endPickedDate!= null){
                  String formattedDate = DateFormat('dd-MM-yyyy').format(endPickedDate);
                  setState(() {
                    endDate.text = formattedDate;
                  }
                  );
                }
              },
            ),

CodePudding user response:

All you need is a check to see if startDate controller is empty or not. If it is not empty show date picker. Check the following code for implementation:

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

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  late TextEditingController startDate;
  late TextEditingController endDate;
  @override
  void initState() {
    startDate = TextEditingController();
    endDate = TextEditingController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextFormField(
          controller: startDate,
          readOnly: true,
          validator: (startDate){
            if(startDate==null|| startDate.isEmpty){
              return "Please Input Start Date";
            }else return null;
          },
          onTap: () async{
            DateTime? startPickedDate = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate:DateTime.now(),
                lastDate: DateTime(2100)
            );
            if(startPickedDate!= null){
              String formattedDate = DateFormat('dd-MM-yyyy').format(startPickedDate);
              setState(() {
                startDate.text = formattedDate; //set output date to TextField value.
              });
            }
          },
        ),

        TextFormField(
          controller: endDate,
          readOnly: true,

          validator: (endDate){
            if(endDate==null || endDate.isEmpty){
              return "Please Input End Date";
            }else {
              return null;
            }
          },
          onTap: () async{
            if (startDate.text.isNotEmpty) {
              String dateTime = startDate.text;
              DateFormat inputFormat = DateFormat('dd-MM-yyyy');
              DateTime input = inputFormat.parse(dateTime);

              DateTime? endPickedDate = await showDatePicker(
                context: context,
                initialDate: input.add(const Duration(days: 1)),
                firstDate:  input.add(const Duration(days: 1)),
                lastDate: DateTime(2100),
              );
              if(endPickedDate!= null){
                String formattedDate = DateFormat('dd-MM-yyyy').format(endPickedDate);
                setState(() {
                  endDate.text = formattedDate;
                }
                );
              }
            } else {
              ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('You need to select Start Date')));
            }
          },
        ),
      ],
    );
  }
}

CodePudding user response:

You can check the text of startDate controller. If it is empty (i.e ''), the date picker will not be triggered.

 controller: endDate,
    readOnly: true,
    validator: (endDate) {
      if (endDate == null || endDate.isEmpty) {
        return "Please Input End Date";
      } else
        return null;
    },
    onTap: () async {
      if (startDate.text.isNotEmpty) {
        DateTime? endPickedDate = await showDatePicker(
           context: context,
           initialDate: DateTime.now(),
           firstDate: DateTime.now(),
           lastDate: DateTime(2100),
        );
        if (endPickedDate != null) {
          String formattedDate = DateFormat('dd-MM-yyyy').format(endPickedDate);
          setState(() {
            endDate.text = formattedDate;
          });
        }
      }
    },
  ),

CodePudding user response:

DateTime? startPickedDate

Define this variable outside the build method. When the start date is selected update this variable. Then in end date add this variable as the first date in date picker

CodePudding user response:

Please update your Text form fields with the below code.

Added Text formfield and the start & end date. I have set 40 days range initially for start and end date. you can update this as per your need.

 TextEditingController startDateController = TextEditingController();
  TextEditingController endDateController = TextEditingController();
  DateTime startDate = DateTime.now().subtract(Duration(days: 40));
  DateTime endDate = DateTime.now().add(Duration(days: 40));

Build method column code

Column(children: [
            TextFormField(
              controller: startDateController,
              readOnly: true,
              validator: (startDate) {
                if (startDate == null || startDate.isEmpty) {
                  return "Please Input Start Date";
                } else
                  return null;
              },
              onTap: () async {
                DateTime? startPickedDate = await showDatePicker(
                    context: context,
                    fieldLabelText: "Start Date",
                    initialDate: startDate,
                    firstDate: startDate,
                    lastDate: endDate);
                if (startPickedDate != null) {
                  String formattedDate =
                      DateFormat('dd-MM-yyyy').format(startPickedDate);
                  setState(() {
                    startDate = startPickedDate;
                    startDateController.text =
                        formattedDate; //set output date to TextField value.
                  });
                }
              },
            ),
            TextFormField(
              controller: endDateController,
              readOnly: true,
              validator: (endDate) {
                if (endDate == null || endDate.isEmpty) {
                  return "Please Input End Date";
                } else
                  return null;
              },
              onTap: () async {
                DateTime? endPickedDate = await showDatePicker(
                  context: context,
                  fieldLabelText: "End Date",
                  initialDate: startDate,
                  firstDate: startDate,
                  lastDate: endDate,
                );
                if (endPickedDate != null) {
                  String formattedDate =
                      DateFormat('dd-MM-yyyy').format(endPickedDate);
                  setState(() {
                    endDate = endPickedDate;
                    endDateController.text = formattedDate;
                  });
                }
              },
            ),
          ]
  • Related