Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a DataTable with Firestore and Flutter (using StreamBuilder)

How to populate a DataTable using StreamBuilder?

Below is my code:

          new StreamBuilder(
            stream: widget._returnStreamWithActiveKeysOnly(),
            builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
              if (!snapshot.hasData) return new Text('Loading...');
              return new DataTable(
                columns: <DataColumn>[
                  new DataColumn(
                    label: Text('type'),
                    tooltip: 'Ordinary or service (1 day only, restricted time)',
                  ),
                  new DataColumn(label: Text('Key')),
                  new DataColumn(label: Text('Check-in')),
                  new DataColumn(label: Text('Check-out')),
                ],
                rows: _listOfRows(snapshot),

              );
            },
          )

I couldn't find a way (like a built-in builder) to indicate the document index to pass to the _listOfRows function, or how to access the current document for each stream.

like image 619
Gustavo Cotta Avatar asked Oct 16 '22 17:10

Gustavo Cotta


1 Answers

I dont know what data comes from your stream, but here is on idea on how to do it:

 DataTable(
   rows: _createRows(snapshot.data),
 )

You want your builder method to return List<DataRow>

  List<DataRow> _createRows(QuerySnapshot snapshot) {

    List<DataRow> newList = snapshot.documents.map((DocumentSnapshot documentSnapshot) {
      return new DataRow(cells: _createCellsForElement(documentSnapshot["someDataYouWantToProcessForCellData"]));
    }).toList();

    return newList;
  }

You can apply the same logic for cell creation, or you can do it inside the first map function as well.

like image 122
Tree Avatar answered Oct 21 '22 07:10

Tree