I am working on a flutter where I have 2 Lists, 1. usersEmails, usersNames
How can I sort that code in a way that 1st element of userEmails and userNames become the 1st Row of data table.
Example:
- List of Emails: [ABC, DEF, GHI]
- List of Names: [MNO, PQR, XYZ]
What I want is:
The Data Rows will depend on the total numbers elements in the Email/Name List.
DataTable(
columns: const [
DataColumn(label: Text('ID'),),
DataColumn(label: Text('Email'),),
DataColumn(label: Text('Name'),),
],
rows: const [
DataRow(cells: [
DataCell(Text("101")),
DataCell(Text("ABC")),
DataCell(Text("MNO")),
]),
DataRow(cells: [
DataCell(Text("102")),
DataCell(Text("DEF")),
DataCell(Text("PQR")),
]),
DataRow(cells: [
DataCell(Text("103")),
DataCell(Text("GHI")),
DataCell(Text("XYZ")),
]),
]
)
CodePudding user response:
Can you try following code.
class _MyHomePageState extends State<MyHomePage> {
List lst = ['ABC', 'DEF', 'GHI'];
List lst2 = ['asdas', 'adsasd', 'dfaas'];
List<DataRow> generateDataRow(List ls) {
List<DataRow> dataRows = [];
//Both list should have same length
//Otherwise it will throw errors.
for (int i=0; i<ls.length; i ) {
dataRows.add(
DataRow(
cells: [
DataCell(Text(ls[i])),
DataCell(Text(lst2[i])),
]
)
);
}
return dataRows;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(16),
child: DataTable2(
columnSpacing: 12,
horizontalMargin: 12,
minWidth: 600,
columns: const [
DataColumn2(
label: Text('Email'),
size: ColumnSize.L,
),
DataColumn(
label: Text('Name'),
),
],
rows: generateDataRow(lst),),
),// This trailing comma makes auto-formatting nicer for build methods.
);
}
}