Multiple Selection in listview.builder Flutter
To create a multiple-selection list using ListView.builder
in Flutter, I’m using a CheckboxListTile
widget for each item in the list.
Here’s an example of how you can do this:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final Set<int> _selectedIndices = Set();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Multiple Selection List'),
),
body: ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
return CheckboxListTile(
value: _selectedIndices.contains(index),
onChanged: (value) {
setState(() {
if (value) {
_selectedIndices.add(index);
} else {
_selectedIndices.remove(index);
}
});
},
title: Text('Item $index'),
);
},
),
),
);
}
}
This code creates ListView
with a CheckboxListTile
widget for each item in the list. The CheckboxListTile
widget handles the selection behavior and displays a checkbox next to each item. When the user selects an item, the onChanged
callback is triggered, and the selected index is added to or removed from the _selectedIndices
set.
You can customize the appearance and behavior of the list items as needed. For example, you can use the title
and subtitle
properties to specify the text for each item or use the trailing
property to add additional widgets to the right of the checkbox. Thank you for Reading.