Search code examples
flutterdartmobilefrontendflutter-getx

type 'Rx<DateTime>' is not a subtype of type 'DateTime' in type cast


I called the showDatePicker function to be used on the registration screen. Since I wrote with getx, I used obs for instant display of the selected value, but I encountered the error as below.

"type 'Rx' is not a subtype of type 'DateTime' in type cast"

class RegisterScreen extends GetWidget<RegisterController> {
  RegisterScreen({Key? key}) : super(key: key);
  static const routeName = "/register_screen";
  DateTime _selectedDate = DateTime.now().obs as DateTime;
  late BuildContext _context;
Obx(() => GestureDetector(
                              onTap: (() async {
                                var initialDate = DateTime.now();

                                _selectedDate = await showDatePicker(
                                      context: context,
                                      initialDate: initialDate,
                                      firstDate: DateTime(1930),
                                      lastDate: DateTime(2100),
                                    ) ??
                                    _selectedDate;
                                print(_selectedDate.toIso8601String());
                              }),
                              child: Card(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(16),
                                ),
                                child: Padding(
                                  padding: const EdgeInsets.all(12.0),
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      const Icon(
                                        FontAwesomeIcons.calendar,
                                        size: 30,
                                      ),
                                      Expanded(
                                        child: Text(
                                          DateFormat("EEE,MMM d")
                                              .format(_selectedDate),
                                          textAlign: TextAlign.center,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            )),

Solution

  • You need to change this:

    DateTime _selectedDate = DateTime.now().obs as DateTime;
    

    to this:

    var _selectedDate = DateTime.now().obs;
    

    And use the value of _selectedDate like this everywhere:

    _selectedDate.value
    

    Check this to know more about GetX.