MDatePicker function

Future<DateTime?> MDatePicker(
  1. BuildContext context, [
  2. DateTime? initDate,
  3. Color color = Colors.black
])

Implementation

Future<DateTime?> MDatePicker(BuildContext context,
    [DateTime? initDate, Color color = Colors.black]) async {
  DateTime? chosenDateTime;
  if (Platform.isIOS) {
    bool isDataChanged = false;
    await showCupertinoModalPopup<dynamic>(
        context: context,
        builder: (_) => Container(
          height: 250,
          color: const Color.fromARGB(255, 255, 255, 255),
          child: Column(children: [
            // Close the modal
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CupertinoButton(
                    padding: EdgeInsets.only(left: 30),
                    child: Text('Cancel'),
                    onPressed: () {
                      if (initDate != null) {
                        chosenDateTime = initDate;
                      }

                      Navigator.of(context, rootNavigator: true).pop();
                    }),
                CupertinoButton(
                    padding: EdgeInsets.only(right: 30),
                    child: Text('Ok'),
                    onPressed: () {
                      if (initDate != null && !isDataChanged) {
                        chosenDateTime = initDate;
                      }

                      chosenDateTime ??= DateTime.now();

                      Navigator.of(context, rootNavigator: true).pop();
                    }),
              ],
            ),
            SizedBox(
              height: 200,
              child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date,
                  initialDateTime:
                  (initDate != null) ? initDate : DateTime.now(),
                  onDateTimeChanged: (val) {
                    isDataChanged = true;
                    chosenDateTime = val;
                  }),
            ),
          ]),
        ));
  } else {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: (initDate != null) ? initDate : DateTime.now(),
      // Refer step 1
      firstDate: DateTime(1900),
      lastDate: DateTime(2025),
      builder: (context, child) {
        return Theme(
          data: ThemeData.light().copyWith(
            primaryColor: color,
            accentColor: color,
            colorScheme: ColorScheme.light(
              primary: color,
            ),
            buttonTheme:
            const ButtonThemeData(textTheme: ButtonTextTheme.primary),
          ),
          child: (child != null) ? child : Text(""),
        );
      },
    );

    if (picked != null && picked != chosenDateTime) {
      DateTime date = picked;
      return date;
    }

    if (picked != null) {
      chosenDateTime = picked;
    }
  }

  return chosenDateTime;
}