Skip to content

Instantly share code, notes, and snippets.

@emri99
Created December 16, 2020 00:06
Show Gist options
  • Save emri99/5e05dcc868546558ac560aaf82240465 to your computer and use it in GitHub Desktop.
Save emri99/5e05dcc868546558ac560aaf82240465 to your computer and use it in GitHub Desktop.
Multiple selection List Flutter
/// Flutter code sample for ListTile.selected
// Here is an example of using a [StatefulWidget] to keep track of the
// selected index, and using that to set the `selected` property on the
// corresponding [ListTile].
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: MyStatefulWidget(),
),
);
}
}
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
List<int> _selectedIndexList = [];
bool _selectionMode = false;
_isSelected(index) => _selectedIndexList.contains(index);
_toggleSelection(index) {
setState(() {
if (_isSelected(index)) {
_selectedIndexList.remove(index);
} else {
_selectedIndexList.add(index);
}
_selectionMode = _selectedIndexList.length > 0;
});
}
_onTap(index) {
if (_selectionMode) {
_toggleSelection(index);
return;
}
print('opening item at index $index');
}
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 10,
itemBuilder: (BuildContext context, int index) {
bool selected = _isSelected(index);
return ListTile(
leading: Wrap(
children: [
GestureDetector(
child: Icon(selected ? Icons.check_box : Icons.check_box_outline_blank),
onTap: () => _toggleSelection(index),
),
SizedBox(width: 8),
Icon(Icons.settings),
],
),
title: Text('Item $index'),
selected: selected,
onTap: () {
_onTap(index);
},
onLongPress: () => _toggleSelection(index),
trailing: _selectionMode ? SizedBox(width: 8) : Icon(Icons.chevron_right),
);
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment