Working with Table in Flutter

Last updated on January 3, 2021 A Goodman Loading... Post a comment

Tables help us to display information in a clear and concise manner. In this article, we’ll take a look at the Table widget in Flutter and walk through a few examples of implementing it in mobile applications. You’ll also learn how to make a Table look much better than default by adding borders and padding, setting columns’s width, etc.

Constructor

At first, let’s check the Table’s constructor:

Table({
  Key key, 
  List<TableRow> children: const <TableRow>[], 
  Map<int, TableColumnWidth> columnWidths, 
  TableColumnWidth defaultColumnWidth: const FlexColumnWidth(1.0), 
  TextDirection textDirection, 
  TableBorder border, 
  TableCellVerticalAlignment defaultVerticalAlignment: TableCellVerticalAlignment.top, 
  TextBaseline textBaseline: TextBaseline.alphabetic
})

Basic example:

Table(
            children: [
              TableRow(children: [
                Text('id'),
                Text('email'),
                Text('name')
              ]),
              TableRow(children: [
                Text('1'),
                Text('[email protected]'),
                Text('Ant-Man')
              ]),
              TableRow(children: [
                Text('2'),
                Text('[email protected]'),
                Text('Batman')
              ])
            ],
          ),

Output:

This table doesn’t look very nice. Don’t worry, we’ll improve it later.

Properties

PropertyTypeDescription
childrenList<TableRow>Takes a list of TableTow as a parameter. TableRow, in turn, can take a list of widgets as children
borderTableBorderThe style to use when painting the boundary and interior divisions
columnWidthsMap<int, TableColumnWidth>Determines the width of the columns
defaultColumnWidthTableColumnWidthDivides up the remaining space in the horizontal axis to determine the column width
defaultVerticalAlignmentTableCellVerticalAlignmentSets the alignment of cells vertically in the table
textBaselineTextBaselineSpecifies a horizontal line uses to align text on the screen inside the the table

Styling a Table

Note: Table isn’t scrollable. If it has too many rows, you should wrap it within a SingleChildScrollView

Rows size vertically based on their contents.

By default, columns of a Table have the same widths. That’s not ideal as some columns need a little space while others need more space. To set width for each column in a Table, we can use the columnWidths property, like this:

columnWidths: {
   0: FixedColumnWidth(50), // this column has a fixed width of 50
   1: FlexColumnWidth(1), // take 1/3 of the remaining space
   2: FlexColumnWidth(2), // // take 2/3 of the remaining space
},

Note: The first column of a table has an index of 0

You can add borders to a Table by using its border property, like this:

border: TableBorder.all(width: 1, color: Colors.purple),

The contents of the table cells are too close together and it would be better to add a bit of padding. You can do so by wrap them inside a Padding or a Container.

Example

Preview:

The code:

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Kindacode.com'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(25),
          child: Table(
            columnWidths: {
              0: FixedColumnWidth(30),
              1: FlexColumnWidth(),
              2: FlexColumnWidth()
            },
            children: [
              TableRow(children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('id'),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('email'),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('name'),
                )
              ]),
              TableRow(children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('1'),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('[email protected]'),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('Ant-Man'),
                )
              ]),
              TableRow(children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('2'),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('[email protected]'),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('Batman'),
                )
              ])
            ],
            border: TableBorder.all(width: 1, color: Colors.purple),
          ),
        ));
  }
}

One More Example: Striped Table

This example create a table whose even rows will have one background color and odd rows will have a different background color.

Preview:

The code:

class MyHomePage extends StatelessWidget {
  // this dummy data will be displayed in the table
  final List<Map> _users = [
    {'id': 1, 'name': 'John'},
    {'id': 2, 'name': 'Bob'},
    {'id': 3, 'name': 'Trump'},
    {'id': 4, 'name': 'Joe Biden'},
    {'id': 5, 'name': 'Superman'},
    {'id': 6, 'name': 'Wonder Lady'},
    {'id': 7, 'name': 'Ronaldo'},
    {'id': 8, 'name': 'Ben'}
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Kindacode.com'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(25),
          child: SingleChildScrollView(
            child: Table(
              columnWidths: {
                0: FixedColumnWidth(50),
                1: FlexColumnWidth(),
              },
              children: _users.map((user) {
                return TableRow(children: [
                  Container(
                      color: _users.indexOf(user) % 2 == 0
                          ? Colors.blue[50]
                          : Colors.amber[50],
                      padding: EdgeInsets.all(15),
                      child: Text(user['id'].toString())),
                  Container(
                      color: _users.indexOf(user) % 2 == 0
                          ? Colors.blue[50]
                          : Colors.amber[50],
                      padding: EdgeInsets.all(15),
                      child: Text(user['name']))
                ]);
              }).toList(),
              border: TableBorder.all(width: 1, color: Colors.black),
            ),
          ),
        ));
  }
}

Conclusion

In this article, we explored the built-in table widget in Flutter. It is really helpful in helping us to neatly display information in rows and columns.

If you’d like to learn more about Flutter and Dart, check out our Flutter category page or Dart category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles