ListDataTable is a custom Flutter widget designed to display tabular data in a list-like format. It’s versatile and can be used with various data types. Here’s a breakdown of its usage and functionality.

Key Properties

  • data: A list of generic type T, representing the data to be displayed in the table.
  • shrinkWrap: A boolean value that determines whether the ListView should adapt its size to its children.
  • controller: An optional ScrollController for the ListView.
  • columns: A list of DataTableHeader objects representing the headers of the table.
  • dataTableItemBuilder: A function that returns a list of DataTableRowCell objects based on the data item. It defines how each data row should be built.
  • onClick: An optional callback function that’s called when a row is tapped.
  • physics: Optional physics for the ListView.

Widget Structure

The widget consists of a Column containing two main elements:
  1. Table Header: Constructed using prepareDataTableHeader() method. It converts DataTableHeader objects into a row of header widgets.
  2. Table Body: A ListView.builder that generates the table rows using prepareDataTableItem(). Each row is an InkWell widget, which makes it tappable and triggers the onClick callback.

Methods

  • prepareDataTableHeader(): Converts the columns list into a row of header widgets, applying the specified flex value to each.
  • prepareDataTableItem(): Takes a list of DataTableRowCell objects and converts them into a row of data widgets, applying the flex value based on the corresponding header.

Usage Example

ListDataTable<MyDataType>(
  data: myDataList,
  columns: [
    DataTableHeader(child: Text('Name')),
    DataTableHeader(child: Text('Age')),
    // More headers...
  ],
  dataTableItemBuilder: (MyDataType dataItem) {
    return [
      DataTableRowCell(Text(dataItem.name)),
      DataTableRowCell(Text(dataItem.age.toString())),
      // More cells...
    ];
  },
  onClick: (MyDataType dataItem) {
    // Handle row tap
  },
)
In this example, MyDataType is the generic type used for the ListDataTable, with myDataList being a list of MyDataType instances. The table has two columns, ‘Name’ and ‘Age’, and the dataTableItemBuilder returns the corresponding DataTableRowCell widgets for each row.

Conclusion

ListDataTable is a flexible and reusable widget that simplifies the process of displaying tabular data in Flutter applications. Its customizable structure and callback support make it suitable for a wide range of use cases.