Flutter - Navigating to detail page on a sfdatagrid row selection (table has data fromfirestore)

724 Views Asked by At

I managed to populate a SfDatagrid table with data from firestore, this is the link to the code:

https://github.com/SyncfusionExamples/How-to-load-data-from-firestore-to-Flutter-DataTable-SfDataGrid-

This code is running perfectly and I have the desired result.

But the problem is that on a table selection I want the app to navigate on a detail page and show more info from the firebase source on the selected row.

But I don't know how I can pass the document snapshot or document index to the detail page when row is selected.

Notice that I am not a pro yet, I'm just getting started.

I tried this:

onCellTap: (DataGridCellTapDetails details) {

              final DataGridRow row = employeeDataGridSource
                 .effectiveRows[details.rowColumnIndex.rowIndex - 1];
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (context) => DataGridRowInfoPage(row: row)));

            },

But it only shows the info on the table, but on the firestore document I have a lots of field and I can't show them all on a table, I wish to show them only on detail page.

1

There are 1 best solutions below

1
On BEST ANSWER

You can get the document index by finding the tapped DataGridRow from the DataGridSource.effectiveRows property and then finding the index from the DataGridSource.dataGridRows property using that row. Now you can fetch the document details from the snapshot by using that index.

Code Snippet:


SfDataGrid(
            source: employeeDataSource,
            columns: getColumns,
            onCellTap: (details) {
              if (details.rowColumnIndex.rowIndex != 0) {
                final DataGridRow row = employeeDataSource
                    .effectiveRows[details.rowColumnIndex.rowIndex - 1];
                int index = employeeDataSource.dataGridRows.indexOf(row);
                var data = snapshot.data!.docs[index];
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (context) => DataGridRowInfoPage(data)));
              }
            },
          );

In DataGridRowInfoPage:


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class DataGridRowInfoPage extends StatefulWidget {
  const DataGridRowInfoPage(this.data, {Key? key}) : super(key: key);

  final QueryDocumentSnapshot<Object?> data;

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

class DataGridRowInfoPageState extends State<DataGridRowInfoPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter DataGrid'),
      ),
      body: Center(
        child: Text('Employee salary: ${widget.data.get('salary')}'),
      ),
    );
  }
}