Articles in this section

How to Load Data into Flutter DataGrid Pages Using JSON in DataTable?

In this article, we will show you how to load data into a DataGrid for each page using JSON in Flutter DataTable.

STEP 1:

Refer to this KB link to populate Flutter DataTable (DataGrid) with JSON API.

STEP 2:

Initialize the SfDataGrid and SfDataPager widgets with all the required properties. Instead of supplying the entire data to the DataGrid, provide only the data corresponding to the current page to the DataGridSource.

Future generateProductList() async {
  // Here we have get the entire data asynchronously.
  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.getRange(0, rowsPerPage).toList());

  return productlist;
}

@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
                  ? LayoutBuilder(builder: (context, constraints) {
                      return Column(children: [
                        SizedBox(
                            height: constraints.maxHeight - 60,
                            width: constraints.maxWidth,
                            child: buildDataGrid()),
                        SizedBox(
                          height: 60,
                          width: constraints.maxWidth,
                          child: SfDataPager(
                            pageCount: (productlist.length / rowsPerPage)
                                .ceil()
                                .toDouble(),
                            delegate: jsonDataGridSource,
                            availableRowsPerPage: const [10, 20, 30],
                            onRowsPerPageChanged: (int? rowsPerPages) {
                              setState(() {
                                rowsPerPage = rowsPerPages!;
                                jsonDataGridSource.updateDataGriDataSource();
                              });
                            },
                          ),
                        )
                      ]);
                    })
                  : const Center(
                      child: CircularProgressIndicator(strokeWidth: 3));
            }));
  }

  Widget buildDataGrid() {
    return SfDataGrid(
        columns: getColumns(),
        source: jsonDataGridSource,
        columnWidthMode: ColumnWidthMode.fill);
  }
STEP 3:

Then, load the relevant data for the specific page within the handlePageChange method. This method is invoked whenever the page is changed through the data pager.

class JsonDataGridSource extends DataGridSource {
 ...

@override
  Future<bool> handlePageChange(int oldPageIndex, int newPageIndex) async {
    int startIndex = newPageIndex * rowsPerPage;
    int endIndex = startIndex + rowsPerPage;
    if (endIndex > productlist.length) {
      endIndex = productlist.length;
    }
    if (startIndex < productlist.length && endIndex <= productlist.length) {
      buildDataGridRow(productlist.getRange(startIndex, endIndex).toList());
      notifyListeners();
    } else {
      dataGridRows = [];
    }

    return true;
  }
}

View the GitHub sample here.

I hope you enjoyed learning how to load data into datagrid for pages using JSON in 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 forums, Direct-Tracl, 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 (0)
Access denied
Access denied