How to use a list of DataRows in a PaginatedDataTable in Flutter?

685 Views Asked by At

I have a DataTable where the user can dynamically add and remove DataRows. Because of that the DataTable can get really big. To improve performance I want do use PaginatedDataTable. But this Widget needs an extra class for the datasource. The basic code for that looks like that:

class DataSource extends DataTableSource {

  int _selectedCount = 0;

  @override
  int get rowCount => list.length;

  @override
  bool get isRowCountApproximate => false;

  @override
  int get selectedRowCount => _selectedCount;

  @override
  DataRow getRow(int index) {

    return DataRow.byIndex(
        index: index,
        cells: <DataCell>[
          DataCell(Text('1')),
          DataCell(Text('2')),
          DataCell(Text('3')),
          DataCell(Text('4')),
        ]);
  }
}

In my old Code I used a DataTable, where I had all the DataRows in a list and it worked fine. Here is a snippet from the Code with the list:

class ExerciseTable extends StatefulWidget {

  @override
  _ExerciseTableState createState() => _ExerciseTableState();
}

class _ExerciseTableState extends State<ExerciseTable> {
  ExerciseDataSource _rowsDataSource;

  List<DataRow> _rowList = [
    DataRow(cells: <DataCell>[
          DataCell(Text('1')),
          DataCell(Text('2')),
          DataCell(Text('3')),
          DataCell(Text('4')),
    ]),
  ];

  void _addRow() {
    _rowList.insert(0,
       DataRow(cells: <DataCell>[
          DataCell(Text('1')),
          DataCell(Text('2')),
          DataCell(Text('3')),
          DataCell(Text('4')),
        ])
    );
  }

  void _removeRow() {
    setState(() {
      _rowList.removeAt(0);
    });
  }

Now I want to use the same list with the DataRows for the PaginatedDataTable but how can I integrate the list in the 'DataSource' Class? I appreciate every answer, would be great if someone knows how to do that :)

1

There are 1 best solutions below

2
On

Integrating PaginatedDataTable on customs needs might be a litte confusing, but you can pass your data source list to the DataSource class (through the constructor), and on the getRow method, using the index you can iterate through your data.

An example might be:

@Override
DataRow getRow(int index) {
 final currentData = yourDataList[index]
 return DataRow.byIndex(
  index: index,
  cells: <DataCell>[
   DataCell(Text('${currentData.name}'},
  ],
 );
}