Generating rows and columns dynamically based on json

Hi, I was looking through the Datagrid widget. But I couldn't find a way to dynamically generate the Datagrid without hardcoding the rows and columns. All examples provided are hardcoding columns/rows. Could you please provide an example on generating both rows and columns dynamically based on the JSON? Thank you


3 Replies

TP Tamilarasan Paranthaman Syncfusion Team September 5, 2022 01:46 PM UTC

Hi Abhilash,


As per your requirements, we have prepared a sample for generating the columns and rows based on the JSON file. In that sample, we have generated the columns and rows based on the JSON key value. Please check the following sample and code snippet,


  List<Product> productlist = [];

  List<GridColumn> columns = [];

  List<String> columnNames = [];

 

  Future generateProductList() async {

    var response = await http.get(Uri.parse(

        'https://ej2services.syncfusion.com/production/web-services/api/Orders'));

 

    var source = json.decode(response.body).cast<Map<String, dynamic>>();

 

    productlist =

        await source.map<Product>((json) => Product.fromJson(json)).toList();

    columns = generateColumns(source);

    jsonDataGridSource = JsonDataGridSource(productlist);

 

    return productlist;

  }

 

  List<GridColumn> generateColumns(var source) {

    List<GridColumn> columns = [];

    final data = source[0] as Map;

    for (var columnName in data.keys) {

      GridColumn gridColumn = GridColumn(

        columnName: columnName,

        label: Container(

          padding: const EdgeInsets.all(8),

          alignment: Alignment.center,

          child: Text(

            columnName,

            overflow: TextOverflow.clip,

            softWrap: true,

          ),

        ),

      );

      columns.add(gridColumn);

      columnNames.add(columnName);

    }

    return columns;

  }

 

  @override

  void initState() {

    super.initState();

  }

 

  @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: columns)

                : const Center(

                    child: CircularProgressIndicator(

                      strokeWidth: 3,

                    ),

                  );

          }),

    );

  }

}

 

class JsonDataGridSource extends DataGridSource {

  JsonDataGridSource(this.productlist) {

    dataGridRows = productlist

        .map<DataGridRow>((dataGridRow) => dataGridRow.getDataGridRow())

        .toList();

  }

 

}

 

class Product {

  factory Product.fromJson(Map<String, dynamic> json) {

    return Product(

      orderID: json['OrderID'],

      customerID: json['CustomerID'],

      employeeID: json['EmployeeID'],

      freight: json['Freight'],

      shipCity: json['ShipCity'],

      verified: json['Verified'],

      orderDate: DateTime.parse(json['OrderDate']),

      shipName: json['ShipName'],

      shipCountry: json['ShipCountry'],

      shippedDate: DateTime.parse(json['ShippedDate']),

      shipAddress: json['ShipAddress'],

    );

  }

 

 

  DataGridRow getDataGridRow() {

    return DataGridRow(cells: [

      DataGridCell<int>(columnName: columnNames[0], value: orderID),

      DataGridCell<String>(columnName: columnNames[1], value: customerID),

      DataGridCell<int>(columnName: columnNames[2], value: employeeID),

      DataGridCell<double>(columnName: columnNames[3], value: freight),

      DataGridCell<String>(columnName: columnNames[4], value: shipCity),

      DataGridCell<bool>(columnName: columnNames[5], value: verified),

      DataGridCell<DateTime>(columnName: columnNames[6], value: orderDate),

      DataGridCell<String>(columnName: columnNames[7], value: shipName),

      DataGridCell<String>(columnName: columnNames[8], value: shipCountry),

      DataGridCell<DateTime>(columnName: columnNames[9], value: shippedDate),

      DataGridCell<String>(columnName: columnNames[10], value: shipAddress),

    ]);

  }

}


Sample Link: https://www.syncfusion.com/downloads/support/directtrac/general/ze/sample571949362


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


Regards,

Tamilarasan



AB Abhilash September 6, 2022 12:06 PM UTC

Thank you for the response. This is generating columns dynamically but here still, we need to manually hardcode DataGridRow as its now depending on a Product model. My query is how to dynamically generate an entire Datagrid(columns & rows) based on the json data, so datagrid can be created for any json table data?

Thank you



TP Tamilarasan Paranthaman Syncfusion Team September 7, 2022 01:49 PM UTC

Hi Abhilash,


We generate the DataGrid rows based on the underlying data collocation which you provide (product). We map the row cell values to the respective column based on the respective model properties. That's the behavior of DataGrid.  You can generate the columns and row cells dynamically based on the JSON data key and model without providing the hardcode values. Also, you need to have a model class for the respective JSON file. Please check the following sample.


Sample Link: https://www.syncfusion.com/downloads/support/directtrac/general/ze/sample-2044097806


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


Regards,

Tamilarasan


Loader.
Up arrow icon