Search code examples
flutterdrop-down-menu

How to add select default in DropdownButtonFormField with data form API?


This is my code. I declare like this :

var selectedEquipment;

this is my code to add default value in dropdown

if(!isNew) {
      setState(() {
        selectedEquipment = intervention['equipment'];
      });
    }

And in my DropdownButton

DropdownButtonFormField(
                  value: selectedEquipment,
                  icon: const Icon(Icons.arrow_drop_down_circle_outlined),
                  iconSize: 24,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Equipment',
                    labelStyle: TextStyle(color: cGrey, fontSize: 14),
                    floatingLabelStyle: TextStyle(color: cPrimary, fontSize: 18, fontWeight: FontWeight.w700),
                  ),
                  items: equipmentList.map((item){
                    return DropdownMenuItem(
                      value: item,
                      child: Text(
                        item['label'],
                        style: const TextStyle(color: Colors.black),
                      ),
                    );
                  }).toList(), 
                  onChanged: (newValue) {
                    setState(() {
                      selectedEquipment = newValue;
                      isEquipment = true;
                    });
                    // selectEquipment(newValue);
                  },
),

When I run, I have this error

enter image description here

Exception has occurred.
_AssertionError ('package:flutter/src/material/dropdown.dart': Failed assertion: line 1606 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1': There should be exactly one item with [DropdownButton]'s value: {id: 27, label: tesy}. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value)


Solution

  • I solved this issue. I added equatable and It works fine now.

    class Equipment {
      late final int id;
      late final String label;
      
      Equipment({required this.id, required this.label});
    
      @override
      bool operator ==(Object other) =>
          identical(this, other) ||
          other is Equipment && runtimeType == other.runtimeType && id == other.id && label == other.label;
    
      @override
      int get hashCode => id.hashCode ^ label.hashCode;
    }