Home > Software engineering >  Null check operator used on a null value on selected DateTime in Flutter
Null check operator used on a null value on selected DateTime in Flutter

Time:12-17

i'm trying to pass selected month and date into a firebase firestore query, but i'm always getting the null check operator on the selected month and year.

here is my code where the error occurs:

ElevatedButton(
                  style: ElevatedButton.styleFrom(
                      shape: StadiumBorder(),
                      backgroundColor: Palette.primaryColor),
                  onPressed: () async {
                    selected = await showMonthYearPicker(
                      context: navigatorKey.currentState!.overlay!.context,
                      initialDate: DateTime.now(),
                      firstDate: DateTime(2022),
                      lastDate: DateTime.now(),
                      builder: (context, child) {
                        print(selected!.year); // => error
                        print(selected!.month); // => error
                        return Column(
                          children: <Widget>[
                            Padding(
                              padding: const EdgeInsets.only(top: 50.0),
                              child: Container(
                                height: 500,
                                width: 800,
                                child: child,
                              ),
                            ),
                          ],
                        );
                      },
                    );
                  },
                  child: Center(child: Text('Choisir mois'))),

PS: selected is declared as DateTime?, I appreciate your help!

CodePudding user response:

selected variable will be assigned once the selecting is completed by dialog. Instead of using ! directly, It is better to check null 1st. You can do

  print("${selected?.year}");  // this will print null for nul case

And the selected value be available (general cases)

onPressed: () async {
  selected = await showMonthYearPicker(....);
  print("${selected.toString()}");
},

I will recommend checking understanding-null-safety .

  • Related