Table in Flutter
Hi. Let’s see why and when we will use the Table Widget in Flutter.
Question: Why we should use Table Widget?
Answer: A table is structured for organizing and displaying information, with data arranged in columns and rows. Tables make it easy to compare pairs of related values (e.g., quarterly sales over several years).
Question: When to use the Table Widget?
Answer: We should use the table widget when we want to have multiple rows with the same width of columns and there are equal data for each column(i.e. table).
GridView have really another approach to use. Don’t be confuse in tables and grids.
Words are cheap Show me code.
Youtube video on Table
Let’s start with empty Scaffold
import 'package:flutter/material.dart';
class TableExample extends StatefulWidget {
@override
_TableExampleState createState() => _TableExampleState();
}
class _TableExampleState extends State<TableExample> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Table Example'),
),
);
}
}
- Add Table widget in the body
- Add TableRow (s) in children of Table widget ( Table can have multiple rows that is why Table widget has children not child. )
- Add TableCell (s) in children of TableRow widget ( TableRow can have multiple columns that is why TableRow widget has children not child. )
- Yeah. Now, this is a place where we can place any widget. Let’s have a Text Widget
TableRow(children: [
TableCell(child: Text('Value 1')),
TableCell(
child: Text('Value 2'),
),
TableCell(child: Text('Value 3')),
TableCell(child: Text('Value 4')),
]),
1. Width is automatically decided by Table Widget. Width is equally divided between TableCells
2. TableCell in each TableRow must be equal in each TableRow, otherwise it will throw this error ‘Every TableRow in a Table must have the same number of children, so that every cell is filled. Otherwise, the table will contain holes’ .
3. Height will be same for each row. It will be equal to highest height of a TableCell.
4. child widget in each TableCell can be at anything you want to show.
5. Table’s children can have only TableRow widgets. It can’t have other widgets in it. Because its children’s type is List<TableRow>.
We have made a small example of Table widget which tries to cover each thing related to it.
Let me know if you find difficult to do this. I would love to solve your problems.
Github Link : https://github.com/viveky259259/flutter_for_people/blob/master/lib/widgets/table.example.dart
#HappyCoding #flutter #widgets #table