Home > OS >  flutter dropdown menu items error when list is empy
flutter dropdown menu items error when list is empy

Time:11-05

I try to fill dropdown menu items from api json. I have "mylist" in code. Sometimes, this list is empty and sometimes list has data.

if myList has data there is no problem. I am having trouble when myList is empty. How can i sove this.

 items: _loginController.loginList[0].myList
          .where((p0) => p0.callType == 1)
          .map(
            (item) => DropdownMenuItem<String>(
              value: item.callId.toString(),
              child: Text(
                item.callId.toString(),
                style: GoogleFonts.ptSansNarrow(
                  textStyle: TextStyle(
                      fontSize: 25,
                      fontWeight: FontWeight.w600,
                      color: Colors.black.withOpacity(.8)),
                ),
              ),
            ),
          )
          .toList(),

CodePudding user response:

You can try this:

var _list = _loginController.loginList[0].myList;
DropdownButton(
    items:_list.isEmpty ? [] : _list.where((p0) => p0.callType == 1)
      .map(
        (item) => DropdownMenuItem<String>(
          value: item.callId.toString(),
          child: Text(
            item.callId.toString(),
            style: GoogleFonts.ptSansNarrow(
              textStyle: TextStyle(
                  fontSize: 25,
                  fontWeight: FontWeight.w600,
                  color: Colors.black.withOpacity(.8)),
            ),
          ),
        ),
      )
      .toList(),
    onChanged: (_) {},
  ),

CodePudding user response:

make your value nullable you would no longer be able to access the dropdown button if no items are available in the list by default it will be disabled

class _MyHomePageState extends State<MyHomePage> {
  String? val; //default value


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: DropdownButton(
          onChanged: (value){},
          value: val, // this is where you need to access it
          items: [].map((e) {
            return DropdownMenuItem(
            value: e,
              child: Text(e),
            )
              ;
          }).toList(),
        
        )));
  }
}
  • Related