I'm trying to dynamically create tables using Dart and Flutter. Something like this The number of table rows will change depending on the the JSON file passed in.
I've read through and done all of the Flutter tutorials I can get my hands on and read through the Documentation on the Table and ListBuilder classes, but none of them quite accomplish what I'm trying to do, because the examples either only dynamically create single ListItems or all the data and/or Widgets are hard-coded.
I've also tried doing this by doing:
Table dynamicTable = new Table(); then dynamically adding children Widgets with
dynamicTable.add(TableRow(
children: [
Text("test1"),
Text("test2"),
Text("test3"),
]
));
But I get an error saying "Cannot add to an unmodifiable list".
Any tips on how to accomplish this would be greatly appreciated.
This function creates a table dynamically:
Widget createTable() {
List<TableRow> rows = [];
for (int i = 0; i < 100; ++i) {
rows.add(TableRow(children: [
Text("number " + i.toString()),
Text("squared " + (i * i).toString()),
]));
}
return Table(children: rows);
}
Suppose you have this model class:
class Person {
final int id;
final String name;
final String email;
final String phone;
const Person({
this.id = 0,
this.name = '',
this.email = '',
this.phone = '',
});
...
}
and you have populated a List of Person with data from an API call:
List<Person> _personList = ...
To generate the TableRow, you can do it using List.generate Dart function:
return Table(
border: TableBorder.all(color: Colors.black),
children: List<TableRow>.generate(
_personList.length,
(index) {
final person = _personList[index];
return TableRow(
children: [
Padding(
padding: EdgeInsets.all(5.0),
child: Text(person.id.toString(), textAlign: TextAlign.center),
),
Padding(
padding: EdgeInsets.all(5.0),
child: Text(person.name, textAlign: TextAlign.center),
),
Padding(
padding: EdgeInsets.all(5.0),
child: Text(person.email, textAlign: TextAlign.center),
),
Padding(
padding: EdgeInsets.all(5.0),
child: Text(person.phone, textAlign: TextAlign.center),
),
],
);
},
growable: false,
),
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With