Provider无法使用时如何向class注入数据? - 颤振
How to inject data into class when Provider can't be used? - Flutter
我真的很难回答这个问题,问的是正确的,甚至是正确的术语,所以请在这里帮助我。在我不知道的正确问题语法下,这可能是一个简单的修复。如果是这样,我会在知道行话后删除。
目标
我想将数据动态添加到我的 Syncfusion DataGrid。
问题
- 我不知道如何将我的动态数据列表获取到我的 DataGridSource
- 无法使用提供者、消费者等,因为 class
中没有上下文
- 不知道如何在 Widget 的 DataGrid Consumer 中调用类型时向 class 构造函数添加参数,我看不到任何可能的方法将参数放入 Consumer 中,因为 DataGris 源很挑剔它得到了什么
- 创建我的数据库实例 class 并将数据注入 DataGrid 源根本不起作用,数据未加载
- 我可以看出这最终是一个状态管理问题,因此如果我在这里只学到一件事,我想学习如何将数据传递给 class 独立于任何小部件而无需标准混乱的 OOP 初始化
- 请注意,我曾尝试使用代理提供程序来初始化数据库数据的方法 - 行不通
如果我的问题没有意义,我可以尝试扩展。但是,我只想使用 Consumer 将数据动态添加到 DataGrid。
这里是我使用带有硬编码数据的消费者的 Syncfusions 编码示例。
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),
];
}
}
你应该初始化并将数据放入 DataGrifWidgetClass 的列表中,并将列表传递给 employeeDataSource,我可以与你分享我的代码
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;
}
我真的很难回答这个问题,问的是正确的,甚至是正确的术语,所以请在这里帮助我。在我不知道的正确问题语法下,这可能是一个简单的修复。如果是这样,我会在知道行话后删除。
目标
我想将数据动态添加到我的 Syncfusion DataGrid。
问题
- 我不知道如何将我的动态数据列表获取到我的 DataGridSource
- 无法使用提供者、消费者等,因为 class 中没有上下文
- 不知道如何在 Widget 的 DataGrid Consumer 中调用类型时向 class 构造函数添加参数,我看不到任何可能的方法将参数放入 Consumer 中,因为 DataGris 源很挑剔它得到了什么
- 创建我的数据库实例 class 并将数据注入 DataGrid 源根本不起作用,数据未加载
- 我可以看出这最终是一个状态管理问题,因此如果我在这里只学到一件事,我想学习如何将数据传递给 class 独立于任何小部件而无需标准混乱的 OOP 初始化
- 请注意,我曾尝试使用代理提供程序来初始化数据库数据的方法 - 行不通
如果我的问题没有意义,我可以尝试扩展。但是,我只想使用 Consumer 将数据动态添加到 DataGrid。
这里是我使用带有硬编码数据的消费者的 Syncfusions 编码示例。
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),
];
}
}
你应该初始化并将数据放入 DataGrifWidgetClass 的列表中,并将列表传递给 employeeDataSource,我可以与你分享我的代码
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;
}