Search code examples
flutterdartnullpopupmenuflutter3.7

Another exception was thrown: Expected a value of type 'PopupMenuItem<dynamic>', but got one of type 'Null'


My code is to create a dynamic PopupMenu :

PopupMenuButton(
                    itemBuilder: (context) =>
                    classifications.map((classificationData) {

                        return (condition)? PopupMenuItem(
                                             child: PointerInterceptor(
                                                   child: menuBuild(
                                                              classificationData)), )
                                              :
                                              // ignore: cast_from_null_always_fails
                                              null as PopupMenuItem;
                                        }).toList(),
                                      )

I get this error in the last update of the flutter :

Another exception was thrown: Expected a value of type 'PopupMenuItem', but got one of type 'Null'

I used to use flutter run --no-sound-null-safety to run the project. But now is not allowed to use it.


Solution

  • List<String> classifications  = ["1","2","3","4"];
    
    PopupMenuButton(
         itemBuilder: (context) => classifications
             .where((element) => element == "2") //Condition
             .map((item) => PopupMenuItem(
                   child: Text(item),
                 ))
             .toList(),
       )