Subair K
Subair K

Reputation: 1880

PaginatedDataTable & Provider

My PaginatedDataTable widget:

var shopData = ShopDataSource();
return PaginatedDataTable(
  header: Text('Shops'),
  columns: [
    DataColumn(label: Text('Shop')),
    DataColumn(label: Text('Type')),
    DataColumn(label: Text('Location')),
    DataColumn(label: Text('Status')),
    DataColumn(label: Text('Actions')),
  ],
  rowsPerPage: 5,
  source: shopData,
);

ShopDataSource class extending DataTableSource like this:

class ShopDataSource extends DataTableSource {
  var _shops;

  // fetch data from provider
  var docProvider = Provider.of(context);

  DataRow getRow(int index) {
  return DataRow.byIndex(cells: [
    // dataCells
  ], index: index);
  }

  @override
  bool get isRowCountApproximate => false;

  @override
  int get rowCount => _shops.length;

  @override
  int get selectedRowCount => 0;
}

My question: How to fetch data from DataProvider class to DataCells.

OR

Any alternate way of fetching data from Firestore with StreamBuilder or without this.

Upvotes: 0

Views: 773

Answers (1)

Subair K
Subair K

Reputation: 1880

After a little research I could solve this with

class ShopTable extends StatelessWidget {
  const ShopTable({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Shop> shops;
    var docProvider = Provider.of<DocumentProvider>(context);
    return StreamBuilder(
      stream: docProvider.fetchShopsAsStream(),
      builder: (context, AsyncSnapshot<QuerySnapshot> snap) {
        shops = snap.data.documents.map((e) => Shop.fromMap(e.data)).toList();
        var shopData = ShopDataSource(shops);
        if (snap.hasData) {
          return PaginatedDataTable(
            header: Text('Shops'),
            columns: [
              DataColumn(label: Text('Shop')),
              DataColumn(label: Text('Type')),
              DataColumn(label: Text('Location')),
              DataColumn(label: Text('Status')),
              DataColumn(label: Text('Actions')),
            ],
            rowsPerPage: 5,
            source: shopData,
          );
        }
        return LinearProgressIndicator();
      },
    );
  }
}

class ShopDataSource extends DataTableSource {
  final List<Shop> shops;

  ShopDataSource(this.shops);

  DataRow getRow(int index) {
    return DataRow.byIndex(cells: [
      DataCell(Text(shops[index].shopName)),
      DataCell(Text(shops[index].phoneNumber)),
      DataCell(Text(shops[index].email)),
      DataCell(Text(shops[index].shopOwner)),
      DataCell(Text(shops[index].shopAddress)),
    ], index: index);
  }

  @override
  bool get isRowCountApproximate => false;

  @override
  int get rowCount => shops.length;

  @override
  int get selectedRowCount => 0;
}

Upvotes: 1

Related Questions