tajihiro
tajihiro

Reputation: 2443

How to add TableRow into Table dynamically with flutter

I'm stack over 3 days. I would like to add TableRow into Table dynamically. However I have no idea how to add TableRows from List data.

Table(
    columnWidths: {
      0: FlexColumnWidth(1.0),
      1: FlexColumnWidth(2.0),
    },
    border: TableBorder.all(),
    defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    children: <TableRow>[
        // HOW CAN I MAKE ITERATION with List length.
    ]),

Please let me know how to do it. Thanks.

Upvotes: 4

Views: 14102

Answers (2)

Krishnamoorthy Acharya
Krishnamoorthy Acharya

Reputation: 4254

Please find simple looping in flutter dart for table

  Widget build(BuildContext context) {
  var list = [{'id':"123123","date":"20/08/2016"},{'id':"123124","date":"26/08/2016"},{'id':"123125","date":"26/08/2016"}]; 
  return Scaffold(
  appBar: AppBar(
  title: Text(widget.title),
  ),
  body: Center(
  child: Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    Text('Recent Claims'),
    Table(
      border: TableBorder.all(color: Colors.black),
      columnWidths: {
        0: FixedColumnWidth(100.0),
        1: FixedColumnWidth(100.0)
      },
      children:[
        for(var item in list )  TableRow(children: [
          Text(item['id']),
          Text(item['date']),
      ])]
       ),
  }

Upvotes: 5

Abion47
Abion47

Reputation: 24661

Create the list beforehand in the build method.

final rows = <TableRow>[];
for (var rowData in myRowDataList) {
  rows.add(TableRow(
    ... // Generate a TableRow using rowData
  ));
}

...

Table(
  columnWidths: {
    0: FlexColumnWidth(1.0),
    1: FlexColumnWidth(2.0),
  },
  border: TableBorder.all(),
  defaultVerticalAlignment: TableCellVerticalAlignment.middle,
  children: rows,
),

Alternatively since Dart 2.3, you can use the for loop within the list declaration itself.

Table(
  columnWidths: {
    0: FlexColumnWidth(1.0),
    1: FlexColumnWidth(2.0),
  },
  border: TableBorder.all(),
  defaultVerticalAlignment: TableCellVerticalAlignment.middle,
  children: [
    for (var rowData in myRowDataList)
      TableData(
        ... // Generate a TableRow using rowData
      ),
  ],
),

Upvotes: 5

Related Questions