Watch video
Deep View in Flutter Data Table
Data Table is a useful widget in Flutter. Today we will look how we can use that to create beautiful apps in Flutter for Android and iOS.
Let’s jump into the code. Start by adding the Data Table widget to your UI.
DataTable( columns:[], rows:[], ... ),
I am writing a method called data Body() to return the Data Table widget that we add it to the main UI.
we will see it later.
Columns represent the header of the Data Table. Rows should be the same number as columns or empty.
We are going to display a list of users.
Create a new folder in lib named it “model” and create a dart file tbable_rows. In dart file create the class Table Details. In the class have three String type variables id, first name and email. Also create the constructor in Android Studio Press Alt+ Insert and return the list of table details.
class TableDetails { late String id, firstname, email; TableDetails( {required this.id, required this.firstname, required this.email}); static List getbldetails() { return [ TableDetails(id: '001', firstname: 'anura', email: 'anura@gmail.com'), TableDetails(id: '002', firstname: 'ranga', email: 'ranga@gmail.com'), TableDetails(id: '003', firstname: 'ranha', email: 'ranha@gmail.com'), TableDetails(id: '004', firstname: 'yash', email: 'yash@gmail.com'),
Set the Columns or Headers for Table
columns: [ DataColumn( label: Text("Id"), numeric: false, tooltip: "This is ID", ), DataColumn( label: Text("First Name"), numeric: false, tooltip: "This is First Name", ), DataColumn( label: Text("Email"), numeric: false, tooltip: "This is Email", ),
],
...
Map Users to Rows
rows: tbldetails .map( (tbledetail) => DataRow( selected: selectedUsers.contains(tbledetail), onSelectChanged: (b){ print("Onselect"); onSelectedRow(b!,tbledetail); }, cells: [ DataCell(Text(tbledetail.id), onTap: () { print('Selected ${tbledetail.id}'); }), DataCell(Text(tbledetail.firstname)), DataCell(Text(tbledetail.email)), ], ), ) .toList()),
Sort the table
We are going to sort the table based on the firstName.We are going to use the ‘sortAscending’ and ‘sortColumnIndex’ to the DataTable. Since we know that firstName is the ‘1’th index, we are setting ‘sortColumnIndex’ to zero.
DataTable( sortAscending: sort, sortColumnIndex: 1,
...
implement the onSort function for each DataColumn. Declare a bool variable ‘sort’ which we will be toggling when user clicks on the ‘firstName’ header, we will toggle the ‘sort’ variable.
you can see the initialisation above in the initState.
@override void initState() { // TODO: implement initState sort = false; selectedUsers = []; tbldetails = TableDetails.getbldetails(); super.initState(); } onSort: (columnIndex, ascending) { setState(() { sort = !sort; }); onSortColum(columnIndex, ascending); Then call the onSortColumn that we are going to write inside the onSort() method.
onSortColum(int columnIndex, bool ascending) { if (columnIndex == 1) { if (ascending) { users.sort((a, b) => a.firstName.compareTo(b.firstName)); } else { users.sort((a, b) => b.firstName.compareTo(a.firstName)); } } } |
ascending’ will toggle when we update the ‘sort’ variable using setState() inside the onSort function.
Add the Checkbox
implement ‘onSelectChanged’ method for each row which will be called each time user clicks on the row and ‘selected’ property to true selects all the checkboxes. Checkboxes will appear for each row when you add this method. But our aim to select the Checkbox for user we select, correct?
onSelectedRow(bool selected, TableDetails tbldetail) async { setState(() { if (selected) { selectedUsers.add(tbldetail); } else { selectedUsers.remove(tbldetail); } });
}
updated to row
DataCell(Text(tbledetail.id), When user click on each row, we will check if the added to the list and set the selected property with true or false like below. ‘true’ makes the user Checkbox selected. onSelectedRow(b!,tbledetail); },
Complete Example
import 'package:flutter/material.dart'; import 'package:learn_datatable/models/table_rows.dart'; class LearnDataTables extends StatefulWidget { const LearnDataTables({Key? key}) : super(key: key); @override State createState() => _LearnDataTablesState(); } class _LearnDataTablesState extends State { late List tbldetails; late List selectedUsers; late bool sort; @override void initState() { // TODO: implement initState sort = false; selectedUsers = []; tbldetails = TableDetails.getbldetails(); super.initState(); } onSortColum(int columnIndex, bool ascending) { if (columnIndex == 1) { if (ascending) { tbldetails.sort((a, b) => a.firstname.compareTo(b.firstname)); } else { tbldetails.sort((a, b) => b.firstname.compareTo(a.firstname)); } } } onSelectedRow(bool selected, TableDetails tbldetail) async { setState(() { if (selected) { selectedUsers.add(tbldetail); } else { selectedUsers.remove(tbldetail); } }); } deleteSelected() async { setState(() { if (selectedUsers.isNotEmpty) { List temp = []; temp.addAll(selectedUsers); for (TableDetails tbledetail in temp) { tbldetails.remove(tbledetail); selectedUsers.remove(tbledetail); } } }); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( title: const Text('DataTableLearn'), ), body: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, verticalDirection: VerticalDirection.down, children: [ Center( child: DataTable( sortAscending: sort, sortColumnIndex: 1, columns: [ const DataColumn( label: Text('ID'), numeric: false, tooltip: 'Table First name', ), DataColumn( label: Text('FirstName'), numeric: false, tooltip: 'Table First name', onSort: (columnIndex, ascending) { setState(() { sort = !sort; }); onSortColum(columnIndex, ascending); }), const DataColumn( label: Text('Email'), numeric: false, tooltip: 'Table First name', ), ], rows: tbldetails .map( (tbledetail) => DataRow( selected: selectedUsers.contains(tbledetail), onSelectChanged: (b){ print("Onselect"); onSelectedRow(b!,tbledetail); }, cells: [ DataCell(Text(tbledetail.id), onTap: () { print('Selected ${tbledetail.id}'); }), DataCell(Text(tbledetail.firstname)), DataCell(Text(tbledetail.email)), ], ), ) .toList()), ), Row(children: [Text('data')],) ], ), ), ), ); } }
We are developing Mobile application and Web application for more details visit our web site www.appslanka.lk
0 Comments