Articles in this section
Category / Section

How to populate Flutter DataTable (DataGrid) with JSON API?

2 mins read

Load the data from JSON to the Flutter DataTable widget by fetching the data from JSON (online) and convert JSON data to the list collection. Then create the rows for the datagrid from the list collection.

The following steps explains how to load the JSON data to Flutter DataTable

STEP 1: To fetch the JSON data from the web, add the following package in the dependencies of pubspec.yaml.

dependencies:
  http: ^0.12.0+4

 

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

import 'dart:convert';
import 'package:intl/intl.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

 

STEP 3: To fetch the data from web API, create an async method. Get the JSON data using http.get method and decode that JSON data. And then, convert the JSON data to the list collection. Here a generateProductList() has been created for fetching JSON data.

Future generateProductList() async {
    var response = await http.get(Uri.parse(
        'https://ej2services.syncfusion.com/production/web-services/api/Orders'));
    var list = json.decode(response.body).cast<Map<String, dynamic>>();
    productlist =
        await list.map<_Product>((json) => _Product.fromJson(json)).toList();
    jsonDataGridSource = _JsonDataGridSource(productlist);
    return productlist;
  }

 

STEP 4: Initialize the SfDataGrid with all the required properties. Here SfDataGrid is wrapped inside the FutureBuilder widget. Load the SfDataGrid  widget when the Snapshot.hasData contains data.

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter DataGrid Sample'),
      ),
      body: Container(
          child: FutureBuilder(
              future: generateProductList(),
              builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
                return snapshot.hasData
                    ? SfDataGrid(
                        source: jsonDataGridSource, columns: getColumns())
                    : Center(
                        child: CircularProgressIndicator(
                          strokeWidth: 3,
                        ),
                      );
              })),
    );
  }

 

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

class _JsonDataGridSource extends DataGridSource {
  _JsonDataGridSource(this.productlist) {
    buildDataGridRow();
  }
 
  List<DataGridRow> dataGridRows = [];
  List<_Product> productlist = [];
 
 
  void buildDataGridRow() {
    dataGridRows = productlist.map<DataGridRow>((dataGridRow) {
      return DataGridRow(cells: [
        DataGridCell<int>(columnName: 'orderID', value: dataGridRow.orderID),
        DataGridCell<String>(
            columnName: 'customerID', value: dataGridRow.customerID),
        DataGridCell<int>(
            columnName: 'employeeID', value: dataGridRow.employeeID),
        DataGridCell<DateTime>(
            columnName: 'orderDate', value: dataGridRow.orderDate),
        DataGridCell<double>(columnName: 'freight', value: dataGridRow.freight),
      ]);
    }).toList(growable: false);
  }
 
  @override
  List<DataGridRow> get rows => dataGridRows;
 
  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    return DataGridRowAdapter(cells: [
      Container(
        alignment: Alignment.centerRight,
        padding: EdgeInsets.all(8.0),
        child: Text(
          row.getCells()[0].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.all(8.0),
        child: Text(
          row.getCells()[1].value,
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        alignment: Alignment.centerRight,
        padding: EdgeInsets.all(8.0),
        child: Text(
          row.getCells()[2].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        alignment: Alignment.centerRight,
        padding: EdgeInsets.all(8.0),
        child: Text(
          DateFormat('MM/dd/yyyy').format(row.getCells()[3].value).toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        alignment: Alignment.centerRight,
        padding: EdgeInsets.all(8.0),
        child: Text(
          row.getCells()[4].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
    ]);
  }
}

 

View example in GitHub. 

Loaded Json data to Flutter data table

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (1)
Please  to leave a comment
AC
Agil Calfarera

How if we get data from JSON? JSON of Assets/data.json?

AC
Agil Calfarera

What I mean is get from Assets/data.json with this line:

{ "chatodics": [ { "id": 1, "voltage": 5.0, "voltage_loc_2": 4.9, "voltage_loc_3": 4.5, "voltage_loc_4": 4.2, "voltage_loc_5": 5.1, "current": 0.2, "timestamp": "2022-08-24T23:21:23.707Z" }, { "id": 2, "voltage": 4.8, "voltage_loc_2": 4.9, "voltage_loc_3": 4.5, "voltage_loc_4": 4.2, "voltage_loc_5": 5.1, "current": 0.3, "timestamp": "2022-08-24T23:43:45.707Z" }, { "id": 3, "voltage": 4.5, "voltage_loc_2": 4.9, "voltage_loc_3": 4.5, "voltage_loc_4": 4.2, "voltage_loc_5": 5.1, "current": 0.4, "timestamp": "2022-08-25T00:03:00.707Z" }, ],}

TP
Tamilarasan Paranthaman

Hi Agil Calfarera,

You can load the data from JSON to the Flutter DataTable widget by fetching the data from JSON (assets file) and converting JSON data to the list collection. Then create the rows for the DataGrid from the list collection.

The following steps explains how to load the JSON data(assets file) to Flutter DataGrid.

Step 1: Add the JSON file location under the assets in the pubspec.yaml file. Please check the following code snippet and reference image.

assets:
    - assets/orderdetails.json

Step 2: Import the following library into the flutter application.

import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:intl/intl.dart';

Step 3: To fetch the data from JSON, create an async method. Get the required JSON data by passing the name of the file through the rootBundle and decode that JSON data. And then, convert the JSON data to the list collection. Here a generateProductList() has been created for fetching JSON data.

  Future generateProductList() async {
    var source = await rootBundle.loadString('assets/orderdetails.json');
    var list = json.decode(source).cast<Map<String, dynamic>>();
    productlist =
        await list.map<Product>((json) => Product.fromJson(json)).toList();
    jsonDataGridSource = JsonDataGridSource(productlist);
    return productlist;
  }

Step 4: Initialize the SfDataGrid with all the required properties. Here SfDataGrid is wrapped inside the FutureBuilder widget. Load the SfDataGrid widget when the Snapshot.hasData contains data.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter DataGrid Sample'),
      ),
      body: FutureBuilder(
          future: generateProductList(),
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            return snapshot.hasData
                ? SfDataGrid(source: jsonDataGridSource, columns: getColumns())
                : const Center(
                    child: CircularProgressIndicator(strokeWidth: 3));
          }),
    );
  }
}

Sample Link: Sample

We hope this helps. Please let us know if you need any further assistance on this.

Regards, Tamilarasan

Access denied
Access denied