Being an app developer we are always at a point when we want to implement the item selection and performs operations on it.

In this article, you will learn how to add the selection of items in your app.

Suppose we only have a name ( String ) and rank ( int ) on our list.

class Item {

String imageUrl;

int rank;

Item(this.imageUrl, this.rank);

}

We need to create two lists, itemList for all items and selectedList for selected items.

List<Item> itemList;

List<Item> selectedList; @override

void initState() {



loadList();

super.initState(); } loadList() {

itemList = List();

selectedList = List();



List.generate(20,(index){

itemList.add(Item("assets/pringles.png", index+1));

} }

Let’s jump into UI.

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: getAppBar()

);

}

For AppBar , I have created a separate widget method because you must have seen in apps when selecting it’s the app bar changes. We also need to update the app bar whenever we are selecting items.

We will check in the selectedList length whether it has any item in the list and change the app bar accordingly.

getAppBar() {

return AppBar(

title: Text(selectedList.length < 1

? "Multi Selection"

: "${selectedList.length} item selected"),

);

}

}

I have created a separate widget for the grid item and has a callback in it which will provide the bool value to tell whether it is selected or not.

Now generate the list.

body: GridView.builder(

itemCount: itemList.length,

gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(

crossAxisCount: 4,

childAspectRatio: 0.56,

crossAxisSpacing: 2,

mainAxisSpacing: 2),

itemBuilder: (context, index) {

return GridItem(

item: itemList[index],

isSelected: (bool value) {

setState(() {

if (value) {

selectedList.add(itemList[index]);

} else {

selectedList.remove(itemList[index]);

}

});

print("$index : $value");

},

key: Key(itemList[index].rank.toString()));

}),

If you see, I have added the item in the selected list in the when the item is selected and removes when the item is deselected.

Now we have implemented the selection the grid, let's implement some action.

I have added the delete button on the AppBar to delete the item in the itemList that are present in the selectedList .

If you are wondering why I am using the key because when I was deleting the values it was only updating in the widget tree but not exactly in the element tree.

To know more about keys in flutter check out

That's it for this article.

Check out the GitHub repo used for this article.

Thanks for reading this article ❤

If I got something wrong 🙈, Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

Check my GitHub repositories.