forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 2
/
user-sortable-columns-and-tables-in-flutter.dart
85 lines (77 loc) · 2.13 KB
/
user-sortable-columns-and-tables-in-flutter.dart
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
// Want to support my work 🤝? https://buymeacoffee.com/vandad
class Language {
final String name;
final Image image;
const Language(this.name, this.image);
Language.dart()
: name = 'Dart',
image = Image.network('https://bit.ly/3yH1Ivj');
Language.rust()
: name = 'Rust',
image = Image.network('https://bit.ly/3lPTqhb');
Language.python()
: name = 'Python',
image = Image.network('https://bit.ly/3iCFCEP');
Language.java()
: name = 'Java',
image = Image.network('https://bit.ly/3CCapJH');
static List<Language> all = [
Language.dart(),
Language.rust(),
Language.python(),
Language.java(),
];
}
extension Sort on List<Language> {
void sortByName(bool ascending) => sort((lhs, rhs) =>
ascending ? lhs.name.compareTo(rhs.name) : rhs.name.compareTo(lhs.name));
}
List<DataRow> rows(List<Language> langs) => langs
.map(
(l) => DataRow(
cells: [
DataCell(
Padding(
padding: const EdgeInsets.all(8.0),
child: l.image,
),
),
DataCell(Text(l.name)),
],
),
)
.toList();
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final List<Language> _langs = Language.all..sortByName(true);
int sortedColumnIndex = 1;
var isSortedAscending = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('WhatsApp')),
body: DataTable(
sortAscending: isSortedAscending,
sortColumnIndex: sortedColumnIndex,
columns: [
DataColumn(label: Text('Image')),
DataColumn(
label: Text('Name'),
onSort: (columnIndex, ascending) {
setState(() {
sortedColumnIndex = columnIndex;
isSortedAscending = ascending;
_langs.sortByName(ascending);
});
},
),
],
rows: rows(_langs),
),
);
}
}