DataTable in Flutter
Do you have some important data to show to your users?
Use DataTable.
The DataTable widget allows you to build a table that automatically sizes its columns according to what’s in the cell and it’s easy to implement,
- Add DataTable Widget and define its Columns
- define each row and the cells in each of them
And Voila, you have the DataTable!
but wait, there’s more,
You can show how the table is sorted, make a column numerical, show that row is selected or not yet filled in and more…
Let’s Get Started…
let’s start with static data, create a Model class for the data,
Add DataTable Widget,
DataTable(
columns:[],
rows:[],
...
),
define its Columns,
`columns: [
DataColumn(
label: Text("`Name`"),
numeric: **false**,
),
DataColumn(
label: Text("`Weapons`"),
numeric: **false**,
),
],
...`
Map data to the Rows
rows: avengers
.map(
(avenger) => DataRow(
selected: selectedAvengers.contains(avenger),
cells: [
DataCell(
Text(avenger.name),
onTap: () {
// write your code..
},
),
DataCell(
Text(avenger.weapon),
),
]),
)
.toList(),
...
And that’s it
And As we all know, In Flutter Everything is a widget, so feel free to put any widget into your data cells.
All the elements of the dataTable provide friendly callbacks, so you can implement how the user should edit, select or sort the data,
Let’s try sorting data,
We are going to use the ‘sort ascending’ and ‘sortColumnIndex’ to the DataTable. Since we know that name is the ‘0’th index, we are setting ‘sortColumnIndex’ to zero.
DataTable(
sortAscending: sort,
sortColumnIndex: 0,
...
implement the onSort function for each DataColumn.
Declare a bool variable ‘sort’ which we will be toggling when a user clicks on the ‘Name’ header, we will toggle the ‘sort’ variable.
List<Avengers> avengers;
List<Avengers> selectedAvengers;
bool sort;
...
DataColumn(
onSort: (columnIndex, ascending) {`
`setState(() {
sort = !sort;
});
onSortColum(columnIndex, ascending);
}),
),
...
Then call the onSortColumn that we are going to write inside the onSort*()* method.
onSortColum(int columnIndex, bool ascending) {
if (columnIndex == 0) {
if (ascending) {
avengers.sort((a, b) => a.name.compareTo(b.name));
} else {
avengers.sort((a, b) => b.name.compareTo(a.name));
}
}
}
And our Avengers Datatable is ready..
Avenger DataTable Demo
Tip: it’s possible that all of your data won’t fit in the horizontal space, for example, on small phones, wrap the widget with a SingleChildScrollView
For complete source code, visit
Yash-Aervadiya/DataTable-Demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com