How To Create A Multiselect Flutter List

We have a stream with items(users), we want to be able to select more than one user and perform any possible action, like deleting a user, verifying a user etc. It's actually quite easy to achieve these. Below is the code that works perfectly in such a situation:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
class ListItem {
  int value;
  String name;

  ListItem(this.value, this.name);
}

class AppUsersScreen extends StatefulWidget {
  const AppDashboardUsersScreen();
  @override
  _AppDashboardUsersScreenState createState() =>
      _AppDashboardUsersScreenState();
}

class _AppDashboardUsersScreenState extends State<AppDashboardUsersScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  List selectedUsers = [];

  List<ListItem> _dropdownItems = [
    ListItem(1, "Select Action"),
    ListItem(2, "Mark as verified"),
    ListItem(3, "Block User(s)"),
    ListItem(4, "Delete User(s)"),
  ];

  List<DropdownMenuItem<ListItem>> _dropdownMenuItems;
  ListItem _selectedItem;
  @override
  void initState() {

    _dropdownMenuItems = buildDropDownMenuItems(_dropdownItems);
    _selectedItem = _dropdownMenuItems[0].value;
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _refreshpage() async {
    setState(() {});
  }

  /**
   * Add/Remove Subscribed keyword
   */
  void onUserSelected(bool selected, uid) {
    if (selected == true) {
      setState(() {
        selectedUsers.add(uid);
      });
    }
  }

  List<DropdownMenuItem<ListItem>> buildDropDownMenuItems(List listItems) {
    List<DropdownMenuItem<ListItem>> items = List();
    for (ListItem listItem in listItems) {
      items.add(
        DropdownMenuItem(
          child: Text(listItem.name),
          value: listItem,
        ),
      );
    }
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: appBarBack(context, Theme.of(context).primaryColor),
      body: RefreshIndicator(
        onRefresh: _refreshpage,
        child: Padding(
          padding: EdgeInsets.all(8),
          child: Column(
            children: [
              Row(
                children: [
                  Text(
                    'Count',
                    style: Theme.of(context).textTheme.headline6,
                  ),
                  Spacer(),
                  Text('Users', style: Theme.of(context).textTheme.headline6),
                  Spacer(),
                  DropdownButton<ListItem>(
                      value: _selectedItem,
                      items: _dropdownMenuItems,
                      onChanged: (value) {
                        setState(() {
                          _selectedItem = value;
                        });
                        print(_selectedItem.name);
                      }),
                ],
              ),
              Expanded(
                child: StreamBuilder(
                  stream: Collection<UserModel>(path: 'users')
                      .streamData(),
                  builder: (context, snapshot) {
                    if (snapshot.hasError) {
                      return UIErrorsMessages.somethingIsNotRightCard(context);
                    }

                    switch (snapshot.connectionState) {
                      case ConnectionState.waiting:
                        return Container(
                          color: Theme.of(context).backgroundColor,
                          child: new Center(
                              child: new CircularProgressIndicator(
                            backgroundColor: Theme.of(context).backgroundColor,
                            valueColor: AlwaysStoppedAnimation(
                                Theme.of(context).accentColor),
                          )),
                        );
                      default:
                        if (snapshot.data != null) {
                          return ListView.builder(
                              shrinkWrap: true,
                              primary: true,
                              physics: AlwaysScrollableScrollPhysics(),
                              itemCount: snapshot.data.length,
                              itemBuilder: (context, index) {
                                UserModel user = snapshot.data[index];
                                return CheckboxListTile(
                                  activeColor: Theme.of(context).accentColor,
                                  title: Text(user.getFullName()),
                                  value: selectedUsers.contains(user.uid),
                                  onChanged: (bool selected) {
                                    //onUserSelected(selected, user.uid);
                                    if (selected == true) {
                                      setState(() {
                                        selectedUsers.add(user.uid);
                                      });
                                    }
                                  },
                                  secondary: Text((index + 1).toString()),
                                );
                              });
                        } else {
                          return Center(
                            child: Text('No Users'),
                          );
                        }
                    }
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

That's it! have any question, then leave a comment.

Related Posts

0 Comments

12345

    00