Articles in this section
Category / Section

How to load data from firebase to Flutter DataTable?

2 mins read

You can load data from Firebase to the Flutter DataTable widget by fetching the data from Firebase and converting the JSON data to list collection. Then, create the rows for the DataGrid from the converted list collection.

The following steps explain how to load the data from the Firebase database for Flutter Datatable:

STEP 1: To get started with Firebase, refer to this link and create the database in Firestore.
In this KB, we have explained with the Firebase data as an example. We will not provide Firebase access files and a key.

STEP 2: To fetch the data from the Firebase, you need to add the following package in the dependencies of pubspec.yaml.

dependencies:
  firebase_core: ^1.3.0
  cloud_firestore: ^2.3.0
  firebase_database: ^7.1.1

 

STEP 3: Import the following library in the flutter application.

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

 

STEP 4: Fetch the data from the Firebase database. And then convert the JSON data to list collection. We have already created KB for converting JSON data to list collection. Refer to that KB, for more information. Initialize the SfDataGrid with all the required details. 

late EmployeeDataSource employeeDataSource;
  List<Employee> employeeData = [];
 
getDataFromDatabase() async {
    var value = FirebaseDatabase.instance.reference();
    var getValue = await value.child('DataGridEmployeeCollection').once();
    return getValue;
  }
 
  Widget _buildDataGrid() {
    return FutureBuilder(
      future: getDataFromDatabase(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.hasData) {
          var showData = snapshot.data;
          Map<dynamic, dynamic> values = showData.value;
          List<dynamic> key = values.keys.toList();
 
          for (int i = 0; i < key.length; i++) {
           final data = values[key[i]];
            employeeData.add(Employee(
                id: data['id'],
                name: data['name'],
                designation: data['designation'],
                salary: data['salary']));
          }
 
          employeeDataSource = EmployeeDataSource(employeeData);
          return SfDataGrid(
            source: employeeDataSource,
            columns: <GridColumn>[
              GridColumn(
                  columnName: 'id',
                  label: Container(
                      padding: EdgeInsets.all(16.0),
                      alignment: Alignment.center,
                      child: Text(
                        'ID',
                      ))),
              GridColumn(
                  columnName: 'name',
                  label: Container(
                      padding: EdgeInsets.all(8.0),
                      alignment: Alignment.center,
                      child: Text('Name'))),
              GridColumn(
                  columnName: 'designation',
                  label: Container(
                      padding: EdgeInsets.all(8.0),
                      alignment: Alignment.center,
                      child: Text(
                        'Designation',
                        overflow: TextOverflow.ellipsis,
                      ))),
              GridColumn(
                  columnName: 'salary',
                  label: Container(
                      padding: EdgeInsets.all(8.0),
                      alignment: Alignment.center,
                      child: Text('Salary'))),
            ],
          );
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }
 
  @override
  void initState() {
    super.initState();
    getDataFromDatabase();
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Syncfusion flutter datagrid firebase demo'),
      ),
      body: _buildDataGrid(),
    );
  }

 

STEP 5: Create data source class extends with DataGridSource for mapping data to the SfDataGrid.

class EmployeeDataSource extends DataGridSource {
  EmployeeDataSource(this.employeeData) {
    _buildDataRow();
  }
 
  List<DataGridRow> _employeeData = [];
  List<Employee> employeeData;
 
  void _buildDataRow() {
    _employeeData = employeeData
        .map<DataGridRow>((e) => DataGridRow(cells: [
              DataGridCell<int>(columnName: 'id', value: e.id),
              DataGridCell<String>(columnName: 'name', value: e.name),
              DataGridCell<String>(
                  columnName: 'designation', value: e.designation),
              DataGridCell<int>(columnName: 'salary', value: e.salary),
            ]))
        .toList();
  }
 
  @override
  List<DataGridRow> get rows => _employeeData;
 
  @override
  DataGridRowAdapter buildRow(
    DataGridRow row,
  ) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((e) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(8.0),
        child: Text(e.value.toString()),
      );
    }).toList());
  }
}

 

Load data from fire base to syncfusion flutter datatable




Conclusion

I hope you enjoyed learning how to load data from firebase to Flutter DataTable.

You can refer to our Flutter DataGrid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Flutter DataGrid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!


Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please  to leave a comment
Access denied
Access denied