So I had a requirement where I had to
create a form field with a drop-down menu with checkable items
So I created a popup menu with PopupMenuItem but then I had 3 problems
- When an item was selected popup was getting dismissed
- Clicking on the checkbox was not updating the checkbox state
- Clicking on the text was not updating the check box
So I solved all these issues like this, this may help you guys
- Set enabled = false in PopupMenuItem and Wrapped the child with a gesture listener for click listeners
- Used StatefulBuilder to update the state
- Solution 1 solved this problem too
Here is the code ->
onTapDown: (details) async {
state.didChange(
await showMenu(
context: context,
position: RelativeRect.fromLTRB(
details.globalPosition.dx,
details.globalPosition.dy,
0,
0,
),
items: itemList.keys
.map(
(e) => PopupMenuItem(
enabled: false,
child: StatefulBuilder(
builder: (BuildContext context,
StateSetter setState) {
return GestureDetector(
onTap: () {
setState(() {
itemList[e] = !itemList[e]!;
});
},
child: Row(
children: [
Expanded(child: Text(e)),
Checkbox(
value: itemList[e],
onChanged: (i) {
setState(() {
itemList[e] = i!;
});
},
),
],
),
);
},
),
),
)
.toList(),
elevation: 8.0,
).then((value) => null) ??
[],
);
}