Home > Mobile >  Flutter - PopupMenuButton - add an item manually after adding items from a list
Flutter - PopupMenuButton - add an item manually after adding items from a list

Time:07-14

I have a PopupMenuButton which displays items from a List.

List<Subject> subjects = [
  Subject(
    name: 'English',
    iconFile: 'english.jpg',
  ),
  Subject(
    name: 'Mathematics',
    iconFile: 'maths.jpg',
  ),
  Subject(
    name: 'Business Studies',
    iconFile: 'business.jpg',
  ),
];

Below is PopupMenuButton code where the list is used to generate the menu items:

child: PopupMenuButton<Subject>(
              color: Color.fromARGB(255, 95, 115, 231),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10)),
              onSelected: _changeSubject,
              itemBuilder: (BuildContext context) {
                return subjects.map((Subject subject) {
                  return PopupMenuItem<Subject>(
                    value: subject,
                    child: Text(subject.name),
                  );
                }).toList();
              },
            ),

This works as intended. Now I want to add another item "Sign Out" below "Business Studies" (as in this image link -> PopupMenuButton) and a divider between them. I don't want to add "Sign Out" to the subjects list. Is it possible to add another PopupMenuItem manually after all the generated items?

CodePudding user response:

`

Subject signOutSubject = Subject(
        name: 'Sign Out',
        iconFile: 'signOut.jpg',
    );

add to the end of the toList() function

 toList()..add(PopupMenuItem<Subject>(
                        value: signOutSubject,
                        child: Text(signOutSubject.name),
                      );)

`

CodePudding user response:

You can do like this. result image

return PopupMenuButton(
      color: const Color.fromARGB(255, 95, 115, 231),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      itemBuilder: (context) => <PopupMenuEntry>[
        ...subjects
            .map((s) => PopupMenuItem(value: s, child: Text(s.name)))
            .toList(),
        const PopupMenuDivider(),
        PopupMenuItem(
          onTap: () {},
          value: "LogOut",
          child: const Text('LogOut'),
        ),
      ],
    );
  • Related