日期选择器未打开

问题描述 投票:0回答:1

我创建了一个日期选择器函数来选择服务日期之后的日期。但是 [错误:flutter/runtime/dart_vm_initializer.cc(41)] 未处理的异常:'package:flutter/src/material/date_picker.dart':断言失败:第 185 行 pos 5:'selectableDayPredicate == null || selectableDayPredicate(initialDate)': 提供的initialDate 2024-05-22 00:00:00.000 必须满足提供的selectableDayPredicate。

class ScheduleServiceView extends StatefulWidget {
  const ScheduleServiceView({Key? key, required this.taskModel})
      : super(key: key);

  final TaskModel taskModel;

  @override
  State<ScheduleServiceView> createState() => _ScheduleServiceViewState();
}

class _ScheduleServiceViewState extends State<ScheduleServiceView> {
  DateTime selectedDate = DateTime.now();
  TextEditingController _dateController = TextEditingController();
  // DateTime selectedDate;
  DateFormat _dateFormat = DateFormat('yyyy-MM-dd');
  Map<String, dynamic>? response;
  ScheduleController? _scheduleController;

 Future<void> _selectDate(BuildContext context, DateTime serviceDate) async {
  DateTime currentDate = DateTime.now();

  DateTime initialDate = serviceDate?.add(Duration(days: 1)) ?? currentDate;

  final DateTime? picked = await showDatePicker(
    context: context,
    initialDate: initialDate,
    firstDate: currentDate,
    lastDate: DateTime(2050),
    selectableDayPredicate: (DateTime day) {
      return !day.isBefore(serviceDate.add(Duration(days: 1))); // Disable dates before or equal to serviceDate
    },
  );

  if (picked != null && picked.isAfter(serviceDate)) {
    setState(() {
      selectedDate = picked;
      _dateController.text = _dateFormat.format(selectedDate);
    });
  }
}



  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scheduleController = ScheduleController();
    response = {
      'status': false,
      'message': 'Silahkan Isi Pilih Tanggal Dengan Benar',
    };
  }

  @override
  Widget build(BuildContext context) {
  
    return Scaffold(
      backgroundColor: thirdColor,
      appBar: AppBar(
        backgroundColor: primaryColor,
        title: const Text(
          'Schedule Service',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w900,
            color: Colors.white,
          ),
        ),
        centerTitle: false,
        elevation: 0,
        automaticallyImplyLeading: false,
        
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              'Choose Date',
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
            ),
            const Text(
              'Set the next pump service schedule',
              style: TextStyle(fontSize: 12),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 15.0),
              child: TextFormField(
                controller: _dateController,
                readOnly: true,
                decoration: const InputDecoration(
                  labelText: 'Select a Date',
                  suffixIcon: Icon(Icons.calendar_today),
                ),
                onTap: () {
                  _selectDate(context,  DateTime.parse(widget.taskModel.date!));
                },
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Please select a date';
                  }
                  return null;
                },
              ),
            ),
            CustomButtonLarge(
              text: 'CONFIRM SCHEDULE',
              textColor: Colors.white,
              buttonColor: primaryColor,
              onTap: () async {

                ProgressDialog pd = ProgressDialog(context: context);
                pd.show(
                  max: 100,
                  msg: 'Sedang Kami Proses....',
                  progressValueColor: primaryColor,
                );
                String productId = widget.taskModel.productId!;
                if(productId.isEmpty){
                   productId = '-';
                }
              
                  
                 response = await _scheduleController!.setSchedule(
                    widget.taskModel.phone!,
                    selectedDate.toString(),
                    widget.taskModel.activityLog!);
                 log("resonse set schedule $response");
                pd.close();
                if (response!['status']) {
                  await _scheduleController!.updateStatusTaskHistory(widget.taskModel.taskId!);
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => const BerandaView(
                        loginStatus: 1,
                        connection: true,
                      ),
                    ),
                  );
                } else {
                  // ignore: use_build_context_synchronously
                  Alert(
                    context: context,
                    style: alertStyleWithoutButton,
                    type: AlertType.error,
                    title: 'Oops',
                    desc: response!['message'],
                  ).show();
                }
              },
            )
          ],
        ),
      ),
    );
  }
}
android flutter datepicker
1个回答
0
投票

通过为

firstDate
提供值,日期选择器将自动禁用该值之前的日期。您无需手动提供
selectableDayPredicate
,因为这可能会与可选日期的内部计算发生冲突,而可选日期也取决于
firstDate
的值。

© www.soinside.com 2019 - 2024. All rights reserved.