0
votes

DropdownButton cause null exception as i am passing string variable in value name parameter.

  String diseases = "Select a disease";

DropdownButton<String>(
    value: diseases,
    items: model.diseases
   .map((String value) {
    return DropdownMenuItem<
    String>(
    value: value,
    child: Text(value),
     );
     }).toList(),
     onChanged: (d) {
     setState(() {
     diseases = d;
     print(
     diseases.toString());
     });
     },
     )

It works fine if I used first selected element from the array value: diseases, by value: model.diseases[0], and it also works fine if I hotreload after changing model.diseases[0] to "diseases" in value

════════ Exception Caught By widgets library ═══════════════════════════════════ The following assertion was thrown building Builder(dirty): 'package:flutter/src/material/dropdown.dart': Failed assertion: line 608 pos 15: 'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': is not true.

Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause. In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=BUG.md

1
I first check if (model.diseases!=null?Dropdownbutton(....) .it not null , i checked it - M.ArslanKhan

1 Answers

1
votes

The error is because the default value you provided does not exist on the list of values, if you want to show label in dropdown menu before any value is selected set the initial value as null and use hint property of the dropdownmenu widget

    String diseases;

DropdownButton<String>(
    hint: Text("Select a disease"),
    value: diseases,
    items: model.diseases
   .map((String value) {
    return DropdownMenuItem<
    String>(
    value: value,
    child: Text(value),
     );
     }).toList(),
     onChanged: (d) {
     setState(() {
     diseases = d;
     print(
     diseases.toString());
     });
     },
     )