Jetpack Compose: Data Tables

DataTables guidelines were introduced on material.io about a year ago. It is currently available for developers on Material Components for Web and Flutter but not available for Android and iOS, yet.
When Jetpack Compose came out, DataTable is inside its material package.
I explored its APIs and here is what I’ve learned.
The following examples are based on Jetpack compose 0.4.0 developer preview.
Data Table: What is it?
Material design guideline states that
Data tables display sets of data across rows and columns.
It is for displaying data in a table format like a spreadsheet.
Simple Data Table

DataTable: a composable function that renders the table itself, cells and data rows.
headerRow: a method inside DataTableChildren class which can be used to provide data for header row.
dataRow: a method inside DataTableChildren class which can be used to provide data for data rows.
Easy, right?
Data Table for Jetpack Compose supports more functionalities:
• Sorting
• Selection
• Pagination
Sorting
Data table supports sorting out of the box.

To add sorting support, the DataTableSorting object is provided with the name “sorting”.
Properties required for DataTableSorting are :
- sortableColumns: accepts a set of columns that are allowed for sorting. In the above example, the price can be sorted.
- onSortRequest: called when sorting is made and gives 2 values —
index: column index where sorting is requested and
isAscending: whether sorting is ascending or descending.
And we can add our own logic for sorting.
Rows are sorted and arrow is added by DataTable automatically.
Selection

For selection support, a new property isSelected is added in MenuItem model.
To make data row selectable, a few extra parameters are added to dataRow.
- selected: whether a row is selected or not
- onSelectedChange: listener that notifies when a selection is made. You just need to update the model’s value.
That’s it. DataTable will render checkboxes automatically for you.
Pagination

To support pagination, add pagination property to DataTable.
DefaultDataTablePagination requires two values.
- initialRowsPerPage: Number of rows on the first page
- availableRowsPerPage: A list of integers that indicate how many rows exist for each page.
DataTable with all features
Jetpack Compose’s DataTable has so many potentials for working with tables.
Here is an example of making coffee menu UI using DataTables which support the topics covered above (Sorting, Pagination, and Selection).

All of the source codes in this article is available on Github.
More Resources
Here is Data Table API Reference where you can learn even more APIs not mentioned in this article.
I hope it helps ❤.