DataTable in Flutter
Last Updated :
01 Aug, 2022
A DataTable is a material design used to display data on a table or in rows and columns. A Data table is used to show the data which have columns and rows as child, a Column is used to set the name of the column, and a Row is used to set the values of the columns. Any column in a DataTable can be sorted based on it in either an ascending or descending order. If sortColumnIndex is not null, the table will be sorted according to the values in the designated column. The sort order is determined by a boolean flag called sortAscending.
For More, Refer to Dart Tutorial.
Syntax in Dart:
DataTable(
// datatable widget
columns: [
// column to set the name
DataColumn(label: Text('Col1'),),
DataColumn(label: Text('Col2'),),
],
rows: [
// row to set the values
DataRow(cells: [
DataCell(Text('ValCol1')),
DataCell(Text('ValCol2')),
]),
],
)
Code Example:
Dart
import 'package:flutter/material.dart' ;
void main() => runApp(SimpleDataTable());
class SimpleDataTable extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false ,
theme: ThemeData.light(),
home: Scaffold(
appBar: AppBar(
title: Text( 'Simple Data Table' ),
),
body:
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
columns: [
DataColumn(label: Text( 'ID' ),),
DataColumn(label: Text( 'Name' ),),
DataColumn(label: Text( 'LastName' ),),
DataColumn(label: Text( 'Age' ),),
],
rows:[
DataRow(cells: [
DataCell(Text( "1" )),
DataCell(Text( "Alex" )),
DataCell(Text( "Anderson" )),
DataCell(Text( "18" )),
]),
DataRow(cells: [
DataCell(Text( "2" )),
DataCell(Text( "John" )),
DataCell(Text( "Anderson" )),
DataCell(Text( "24" )),
]),
]
),
),
),
);
}
}
|
Code Explanation:
- main is a Principal Method called once the Program is Loaded.
- Once the Program is Loaded runApp will Run and Call the Class that we Created (SimpleDataTable) to be Executed.
- This Class is a Stateless Widget as the Data showed will be Fixed (No Change).
- As Flutter is based on Widgets, a Widget must be Built.
- Creating a MaterialApp that allows us to use Scaffold.
- Scaffold allows us to use AppBar and Body.
- The AppBar has a Simple Title.
- Body Contain SingleChildScrollView used to Scroll Horizontally and Avoid Overflow due to Mobile with Low Screen Width.
- SingleChildScrollView takes Single Child DataTable which takes Columns and Rows.
- Columns represented in DataColumn that take a Label.
- Rows represented in DataRow take Cells followed by DataCell that takes any Widget representing each Column Value of the Row.
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...