티스토리 뷰

플러터에서 드롭다운(Dropdown) 위젯을 사용하는데 아래와 같은 에러가 발생했다.

DropdownButton(
    value: selectedGroup,
    items: groupList.map((group) {
        return DropdownMenuItem(
            value: group, child: Text(group.name));
    }).toList(),
),
======== Exception caught by widgets library =======================================================
The following assertion was thrown building NewPrayer(dirty, state: _NewPrayerState#7b00b):
There should be exactly one item with [DropdownButton]'s value: Instance of 'Group'. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 890 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1'

 

에러의 원인은 DropdownButton의 value가 items에 없거나 2개 이상이라서 발생했다고 한다.

그리고 이 에러를 발생시킨 assertion의 내용에는 더 많은 정보를 제공한다. 이를 정리하면 다음과 같은 경우 에러가 발생한다고 한다.

1. items가 null인 경우

2. items가 비어있는 경우 (isEmpty)

3. value가 null인경우

4. items에 value가 없는 경우 (속성 기준이 아닌 hashCode 기준)

5. items에 중복된 값이 있는 경우 (속성 기준이 아닌 hashCode 기준)

 

DropdownButton을 만들 때, value에는 selectedGroup을 전달하고 items은 selectedGroup인 포함된 groupList로 DroupdwonMenuItem을 잘 만들어서 전달하였다. 하지만 문제점은 groupList가 깊은 복사를 하게 되면서 selectedGroup이 다른 인스턴스로 만들져서 groupList에 포함되어 버렸다. 그래서 플러터는 items에 value가 없다고 판단하고 에러가 발생한 것이었다.

댓글
공지사항