Selectable List View In Flutter
This article will help, if you are developing a flutter application that needs to select the list items, like in a chat-app to delete the selected chats, or in a todo-app to remove or tick the selected todos.
Find the updated article here.
STEP 1: Place your ListView inside a Stateful Widget
This step is although not necessary if you are using some state managements other than setState() like Bloc, or Provider.
I have chosen the setState() state management with Stateful Widget for simplicity.
class SelectListItem extends StatefulWidget{
@override
_SelectListItemState createState() => _SelectListItemState();
}
class _SelectListItemState extends State<SelectListItem>{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text(‘Select List Items’)),
body: ListView()
}
STEP 2: Add items to your ListView
Here I’m using the ListView builder (instead of ListView above) to generate list-items for me, which are nothing but text widgets displaying the index of the builder function.
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index){
return ListTile(title: Text(‘$index’));
},
),
STEP 3: Create a list variable to store the data of selected list-items
Remember! the data you are storing must be unique to a list-item. This will act as an identifier to select or unselect a specific list-item.
In my case, the index of each item would be unique. So, I’m creating a list of integers to store selected list-items.
List<int> _selectedItems = List<int>();
STEP 4: Now add list-item to our selected-items list on ListTile long-press and change the state (use for changing the state is revealed at step 6)
onLongPress: (){
if(! _selectedItems.contains(index)){
setState(() {
_selectedItems.add(index);
});
}
},
STEP 5: Add onTap function of ListTile to remove the selected item and change the state (use for changing the state is revealed at next step)
onTap: (){
if(_selectedItems.contains(index)){
setState(() {
_selectedItems.removeWhere((val) => val == index);
});
}
},
STEP 6: Wrap the ListTile is a Container to visually separate the selected items from the unselected ones, by changing the color of the Container.
Container(
color: (_selectedItems.contains(index))
? Colors.blue.withOpacity(0.5)
: Colors.transparent,
child: ListTile( …… )
);
All Done! Now you can use the _selectedItems list, to perform some operation on selected items.
Get full source code from here.
Tell Us if you liked this article by clapping :-)
Please comment to share your thoughts with us.