FLUTTER - Redirect to another page when clicking on the row on a SfDatagrid Table

103 views Asked by At

I want to redirect to another page with the "MetarialPageRoute" function when clicking on the line. How can I do that using SfDataGrid when I am populating the table with data from Firestore?

Bellow is my Firestore screenshot. enter image description here

Here as you can see I have 3 users with unique ID. They are all displayed on the table bellow. My output: enter image description here

Now I want to navigate to the profile page where all the details of the selected user will be seen.

Bellow is my SfDatagrid Table code:

    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:dtser/Pages/Users/user_data_model.dart';
    import 'package:dtser/constants/constants.dart';
    import 'package:flutter/material.dart';
    import 'package:syncfusion_flutter_datagrid/datagrid.dart';
    
    class Usuarios extends StatefulWidget {
      const Usuarios({Key? key}) : super(key: key);
    
      @override
      State<Usuarios> createState() => _UsuariosState();
    }
    
    class _UsuariosState extends State<Usuarios> {
      late UserDataSource userDataSource;
      List<UserDataModel> userData = [];
    
      final getData = FirebaseFirestore.instance.collection('users').snapshots();
    
      List<GridColumn> get getColumns {
        return <GridColumn>[
          GridColumn(
            columnName: 'fullName',
            label: Container(
              padding: const EdgeInsets.all(16.0),
              alignment: Alignment.center,
              child: const Text(
                'Nome Completo',
              ),
            ),
          ),
          GridColumn(
            columnName: 'emailAddress',
            label: Container(
              padding: const EdgeInsets.all(16.0),
              alignment: Alignment.center,
              child: const Text('Email'),
            ),
            allowFiltering: true,
          ),
          GridColumn(
            columnName: 'phoneNumber',
            label: Container(
              padding: const EdgeInsets.all(8.0),
              alignment: Alignment.center,
              child: const Text(
                'Telefone',
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          GridColumn(
            columnName: 'dateCreated',
            label: Container(
              padding: const EdgeInsets.all(8.0),
              alignment: Alignment.center,
              child: const Text(
                'Criado',
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          GridColumn(
            columnName: 'lastSingIn',
            label: Container(
              padding: const EdgeInsets.all(8.0),
              alignment: Alignment.center,
              child: const Text(
                'Ăšltimo Login',
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          GridColumn(
            columnName: 'category',
            label: Container(
              padding: const EdgeInsets.all(8.0),
              alignment: Alignment.center,
              child: const Text('Categoria'),
            ),
          ),
        ];
      }

  Widget _buildDataGrid() {
    return StreamBuilder(
      stream: getData,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasData) {
          if (userData.isNotEmpty) {
            // to update the value changed at runtime
            getDataGridRowFromDataBase(DocumentChange<Object?> data) {
              return DataGridRow(
                cells: [
                  DataGridCell<String>(
                    columnName: 'fullName',
                    value: data.doc['fullName'],
                  ),
                  DataGridCell<String>(
                    columnName: 'emailAddress',
                    value: data.doc['emailAddress'],
                  ),
                  DataGridCell<String>(
                    columnName: 'phoneNumber',
                    value: data.doc['phoneNumber'],
                  ),
                  DataGridCell<String>(
                      columnName: 'dateCreated',
                      value: data.doc['dateCreated'].toString()),
                  DataGridCell<String>(
                    columnName: 'lastSignIn',
                    value: data.doc['lastSignIn'].toString(),
                  ),
                  DataGridCell<String>(
                    columnName: 'category',
                    value: data.doc['category'].toString(),
                  ),
                ],
              );
            }

            for (var data in snapshot.data!.docChanges) {
              if (data.type == DocumentChangeType.modified) {
                if (data.oldIndex == data.newIndex) {
                  userDataSource.dataGridRows[data.oldIndex] =
                      getDataGridRowFromDataBase(data);
                }
                userDataSource.updateDataGridSource();
              } else if (data.type == DocumentChangeType.added) {
                userDataSource.dataGridRows
                    .add(getDataGridRowFromDataBase(data));
                userDataSource.updateDataGridSource();
              } else if (data.type == DocumentChangeType.removed) {
                userDataSource.dataGridRows.removeAt(data.oldIndex);
                userDataSource.updateDataGridSource();
              }
            }
          } else {
            for (var data in snapshot.data!.docs) {
              userData.add(
                UserDataModel(
                  fullName: data['fullName'],
                  emailAddress: data['emailAddress'],
                  phoneNumber: data['phoneNumber'],
                  dateCreated: data['dateCreated'].toString(),
                  lastSignIn: data['lastSignIn'].toString(),
                  category: data['category'],
                ),
              );
            }
            userDataSource = UserDataSource(userData);
          }
          return SfDataGrid(
            selectionMode: SelectionMode.single,
            navigationMode: GridNavigationMode.row,
            allowSorting: true,
            source: userDataSource,
            columns: getColumns,
            columnWidthMode: ColumnWidthMode.fill,
            onCellTap: (DataGridCellTapDetails details) {
              final DataGridRow row = userDataSource
                  .effectiveRows[details.rowColumnIndex.rowIndex - 1];
              debugPrint("$row");
            },
          );
        } else {
          return Center(
            child: CircularProgressIndicator(
              color: kDark,
              strokeWidth: 4.0,
            ),
          );
        }
      },
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: Card(
                  child: Text('CARD 1'),
                  color: kActive,
                ),
              ),
              Expanded(
                child: Card(
                  child: Text('CARD 2'),
                  color: kActive,
                ),
              ),
              Expanded(
                child: Card(
                  child: Text('CARD 3'),
                  color: kActive,
                ),
              ),
            ],
          ),
          _buildDataGrid(),
        ],
      ),
    );
  }
}

class UserDataSource extends DataGridSource {
  UserDataSource(this.userData) {
    _buildDataRow();
  }

  List<DataGridRow> dataGridRows = [];
  List<UserDataModel> userData;

  void _buildDataRow() {
    dataGridRows = userData
        .map<DataGridRow>(
          (e) => DataGridRow(
            cells: [
              DataGridCell<String>(
                columnName: 'fullName',
                value: e.fullName,
              ),
              DataGridCell<String>(
                columnName: 'emailAddress',
                value: e.emailAddress,
              ),
              DataGridCell<String>(
                columnName: 'phoneNumber',
                value: e.phoneNumber,
              ),
              DataGridCell<String>(
                columnName: 'dateCreated',
                value: e.dateCreated,
              ),
              DataGridCell<String>(
                columnName: 'lastSignIn',
                value: e.lastSignIn,
              ),
              DataGridCell<String>(
                columnName: 'category',
                value: e.category,
              ),
            ],
          ),
        )
        .toList();
  }

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter buildRow(
    DataGridRow row,
  ) {
    return DataGridRowAdapter(
      cells: row.getCells().map<Widget>(
        (e) {
          return Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.all(8.0),
            child: Text(e.value.toString()),
          );
        },
      ).toList(),
    );
  }

  void updateDataGridSource() {
    notifyListeners();
  }
}

I hope my question is clear. Please let me know if you need any other information.

Thank you in advance for helping!

0

There are 0 answers