How to inject data into class when Provider can't be used? – Flutter

Issue

Im really struggling with this question, asking it right and even proper terminology so please help me out here. This is probably an easy fix under the proper question syntax that I’m unaware of. If so I’ll delete once I know the lingo.

Goal

I want to dynamically add data to my Syncfusion DataGrid.

Problem

  • I don’t know how to get my List of dynamic data to my DataGridSource
  • Can’t use Provider, Consumer etc because of no context in class
  • Don’t know how to add arguments to class constructor when calling type in DataGrid Consumer in Widget, I don’t see any possible way to get an argument into the Consumer as DataGris source is picky about what it gets
  • creating instance of my database class and injecting data into DataGrid source is not working at all, the data does not load
  • I can see that ultimately this is a state management issue, therefore if I learn only one thing here I would like to learn how to pass data to a class independent of any widget without standard messy OOP initializations
  • Note, i did attempt using proxy provider for initializing the database data method- no worky

If my questions don’t make sense I can try to expand. However all i want to do is use Consumer to DYNAMICALLY add data to DataGrid.

Here is Syncfusions coded example for me using consumer with hardcoded data.

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

class DataGridWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<EmployeeDataSource>(
      builder: (context, employeeDataSource, _) {
        return Scaffold(
          appBar: AppBar(
            title: Text('DataGrid Demo'),
          ),
          body: SfDataGrid(
            source: employeeDataSource,
            columnWidthMode: ColumnWidthMode.fill,
            selectionMode: SelectionMode.multiple,
            navigationMode:
                GridNavigationMode.cell, // controller: dataGridController,
            onQueryRowHeight: (details) {
              return details.rowHeight;
            },
            columns: <GridColumn>[
              GridTextColumn(
                  columnName: 'id',
                  label: Container(
                      padding: EdgeInsets.all(16.0),
                      alignment: Alignment.centerRight,
                      child: Text(
                        'ID',
                      ))),
              GridTextColumn(
                  columnName: 'name',
                  label: Container(
                      padding: EdgeInsets.all(16.0),
                      alignment: Alignment.centerLeft,
                      child: Text('Name'))),
              GridTextColumn(
                  columnName: 'designation',
                  width: 120,
                  label: Container(
                      padding: EdgeInsets.all(16.0),
                      alignment: Alignment.centerLeft,
                      child: Text('Designation'))),
              GridTextColumn(
                  columnName: 'salary',
                  label: Container(
                      padding: EdgeInsets.all(16.0),
                      alignment: Alignment.centerRight,
                      child: Text('Salary'))),
            ],
          ),
        );
      },
    );
  }
}

/// Custom business object class which contains properties to hold the detailed
/// information about the employee which will be rendered in datagrid.
class Employee {
  /// Creates the employee class with required details.
  Employee(this.id, this.name, this.designation, this.salary);

  /// Id of an employee.
  int id;

  /// Name of an employee.
  String name;

  /// Designation of an employee.
  String designation;

  /// Salary of an employee.
  int salary;
}

class EmployeeDataSource extends DataGridSource {

  EmployeeDataSource() {
    employees = getEmployeeData();
    buildDataGridRow();
  }

  void buildDataGridRow() {
    dataGridRows = employees
        .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();
  }

  List<Employee> employees = <Employee>[];

  List<DataGridRow> dataGridRows = [];

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

  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((e) {
      return Container(
        alignment: (e.columnName == 'id' || e.columnName == 'salary')
            ? Alignment.centerRight
            : Alignment.centerLeft,
        padding: EdgeInsets.all(8.0),
        child: Text(e.value.toString()),
      );
    }).toList());
  }

  List<Employee> getEmployeeData() {
    return [
      Employee(10001, 'James', 'Project Lead', 20000),
      Employee(10002, 'Kathryn', 'Manager', 30000),
      Employee(10003, 'Lara', 'Developer', 15000),
      Employee(10004, 'Michael', 'Designer', 15000),
      Employee(10005, 'Martin', 'Developer', 15000),
      Employee(10006, 'Newberry', 'Developer', 15000),
      Employee(10007, 'Balnc', 'Developer', 15000),
      Employee(10008, 'Perry', 'Developer', 15000),
      Employee(10009, 'Gable', 'Developer', 15000),
      Employee(10010, 'Grimes', 'Developer', 15000),
      Employee(10010, 'Lane', 'Project Lead', 20000),
      Employee(10010, 'Doran', 'Developer', 15000),
      Employee(10010, 'Betts', 'Developer', 15000),
      Employee(10010, 'Tamer', 'Manager', 30000),
      Employee(10001, 'James', 'Project Lead', 20000),
      Employee(10002, 'Kathryn', 'Manager', 30000),
      Employee(10003, 'Lara', 'Developer', 15000),
      Employee(10004, 'Michael', 'Designer', 15000),
      Employee(10005, 'Martin', 'Developer', 15000),
      Employee(10006, 'Newberry', 'Developer', 15000),
      Employee(10007, 'Balnc', 'Developer', 15000),
      Employee(10008, 'Perry', 'Developer', 15000),
      Employee(10009, 'Gable', 'Developer', 15000),
      Employee(10010, 'Grimes', 'Developer', 15000),
      Employee(10010, 'Lane', 'Project Lead', 20000),
      Employee(10010, 'Doran', 'Developer', 15000),
      Employee(10010, 'Betts', 'Developer', 15000),
      Employee(10010, 'Tamer', 'Manager', 30000),
    ];
  }
}

Solution

you should initialize and putting data in list in DataGrifWidgetClass and pass the lists into employeeDataSource, i can share my code with you

for(int i = 0; i <data.length; i++){
  var split = data[i]["created_at"].toString().split("T");
  cellsList.add(Cells([
    DataCell(dataCells(context,(i+1).toString(),)),
    DataCell(dataCells(context,split[0])),
    DataCell(dataCells(context,data[i]["type"])),
    DataCell(dataCells(context,data[i]["bonus_from"].toString())),
    DataCell(dataCells(context,data[i]["amount"].toString(),color: Colors.green)),
    DataCell(dataCells(context,data[i]["status"].toString())),
  ] ));
}
return Padding(
  padding: const EdgeInsets.symmetric( vertical: 20),
  child: Column(
    mainAxisSize: MainAxisSize.min,
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Text(
        "Bonus History",
        style: robotoStyle(
          context,
          color: Theme.of(context).primaryTextTheme.bodyText1.color,
          fontWeight: FontWeight.bold,
          fontSize: ResponsiveFlutter.of(context).fontSize(Utils.isTabletView == true?1.5:2.25),
        ),
      ),
      SizedBox(
        height: 10,
      ),
      Flexible(
        child: Card(

          color: Theme.of(context).primaryColor,elevation: 0,shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15),

            side: BorderSide(
                color: Theme.of(context).primaryTextTheme.bodyText1.color)),
          child: CardlessHeadlessPaginatedDataTable(
            footer:provider["BonusAccounts"]["data"].length ==0?false: true,
            nextPage: provider["BonusAccounts"]["next_page_url"],
            previousPage: provider["BonusAccounts"]["prev_page_url"],
            firstPage: provider["BonusAccounts"]["first_page_url"],
            rowsPerPage:provider["BonusAccounts"]["data"].length ==0?1: provider["BonusAccounts"]["per_page"],
            columns: <DataColumn>[
              DataColumn(label: currencyTabs(context,"Serial No.")),
              DataColumn(label: currencyTabs(context,"Date")),
              DataColumn(label: currencyTabs(context,"Type")),
              DataColumn(label: currencyTabs(context,"Form")),
              DataColumn(label: currencyTabs(context,"Amount")),
              DataColumn(label: currencyTabs(context,"Status")),
            ],
            source:  DataSource(context,cellsList),
          ),
        ),
      ),
    ],
  ),
);








    class DataSource extends DataTableSource {
      final cellsList;
      DataSource(this.context,this.cellsList) {
    
        // _rows = list;
      }
    
      final BuildContext context;
      List<DataTableRows> _rows;
    
    
      int _selectedCount = 0;
    
      @override
      DataRow getRow(int index) {
        assert(index >= 0);
    
    
            if(cellsList.length != index)
              {
                if(index%2 ==0) {
                  return DataRow(
    
                    color: MaterialStateProperty.all(Theme
                        .of(context)
                        .primaryColor),
                    cells: [
                      for(int j = 0; j < cellsList[index].cells.length; j++)
                        cellsList[index].cells[j],
    
                    ],
                  );
                }else{
                  return DataRow(
                    color: MaterialStateProperty.all(Theme
                        .of(context)
                        .bottomAppBarColor),
                    cells: [
                      for(int j = 0; j < cellsList[index].cells.length; j++)
                        cellsList[index].cells[j],
    
                    ],
                  );
                }
              }
      }
    
      @override
      int get rowCount => cellsList.length;
    
      @override
      bool get isRowCountApproximate => false;
    
      @override
      int get selectedRowCount => _selectedCount;
    }

Answered By – Hamza Siddiqui

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *