I got a project, where a table widget was used instead of DataTable, So I have been able to pull my JSON data to the table row, but I am having issues showing the header for the table, I can use DataTable to achieve, but I am required to use the table widget.
This is what I have done so far
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: list.isEmpty
? Container(
alignment: Alignment.center,
child: CircularProgressIndicator())
: Table(
columnWidths: const <int, TableColumnWidth>{
0: FixedColumnWidth(50),
1: FixedColumnWidth(300),
2: FixedColumnWidth(150),
3: FixedColumnWidth(300),
4: FixedColumnWidth(150),
5: FixedColumnWidth(300),
6: FixedColumnWidth(300),
},
children: list
.map((item) => _buildTableRow(
item, context))
.toList(),
),
)
This is my build row function
TableRow _buildTableRow(UserModel item, context) {
return TableRow(key: ValueKey(item.id), children:
[
tablecell(item.name),
tablecell(item.email),
tablecell(item.phone),
]
}
The challenge is to add titles to the table.
CodePudding user response:
You can use decoration property of 'TableRow' like following, to make it look like header :
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: list.isEmpty
? Container(
alignment: Alignment.center,
child: CircularProgressIndicator())
: _tableWidget(list),
)
// Table widget method :
Widget _tableWidget(list) {
if (list == null) {
return Container();
}
int rowLength = list.length 1; // 1 for titles
List<TableRow> rows = [];
for (int i = 0; i < rowLength; i ) {
List<Widget> columns = [];
bool isHeader = i == 0;
columns.add(tablecell(isHeader ? "Name" : list[i - 1].name));
columns.add(tablecell(isHeader ? "Email" : list[i - 1].email));
columns.add(tablecell(isHeader ? "Phone" : list[i - 1].phone));
rows.add(TableRow(
decoration: isHeader ? _selectedDecoration() : _deselectedDecoration(),
children: columns,
));
}
try {
return Table(
defaultColumnWidth: IntrinsicColumnWidth(),
border: null,
children: rows,
);
} catch (e) {
return Text(e.toString());
}
}
// Modify these according to your requirement
_selectedDecoration() {
return BoxDecoration(
borderRadius: BorderRadius.circular(4.0),
color: Colors.lightBlue,
);
}
_deselectedDecoration() {
return BoxDecoration(
borderRadius: BorderRadius.circular(4.0),
color: Colors.white,
);
}
CodePudding user response:
You can do
children:[
/// your Header
...list.map((item) => _buildTableRow(item, context)).toList(),
]