Search code examples
flutterdatedatepickerdependenciesflutter-dependencies

How to use readonly property in date picker in flutter


I am trying to use the read only property in date picker but unable to do so.

Future<void> SelectSpouseDOB(BuildContext context) async {
    DateTime? pickedDate = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(1970),
      lastDate: DateTime(2101),
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: ThemeData.dark().copyWith(
            // Customize the color scheme
            colorScheme: ColorScheme.dark(
              primary: Color.fromARGB(
                  255, 250, 174, 52), // Header and selected day color
              onPrimary: Color.fromARGB(255, 247, 244,
                  244), // Header text and selected day text color
              surface: const Color.fromARGB(
                  255, 171, 2, 58), // Calendar background color
              onSurface: Color.fromARGB(255, 12, 12, 12), // Calendar text color
            ),
            dialogBackgroundColor: Color.fromARGB(
                255, 231, 142, 142), // Background color of the dialog
          ),
          child: child!,
        );
      },
    );

if (pickedDate != null) {
  // Format the pickedDate as "dd,MM,yyyy"
  final formattedDate = DateFormat('dd-MM-yyyy').format(pickedDate);
  spousedateOfBirthController.text = formattedDate;
 }
}

I want to add the readOnly property there. The user should note be able to write any alphabets within


Solution

  • Your question needs to be properly formatted,

    I assume that your spousedateOfBirthController is attached to TextField, you need to set the property readOnly to that TextField so your code becomes:

    TextField(
      controller: spousedateOfBirthController,
      readOnly: true,
    ),
    

    you can use the attribute onTap to open your date picker pop up or wrap the TextField in a GestureDetector & AbsorbPointer as follows:

    GestureDetector(
      onTap: (){
        //open your popup
      },
      child: AbsorbPointer(
        child: TextField(
          controller: spousedateOfBirthController,
          readOnly: true,
        ),
      ),
    );