When displaying data coming from a database, you often don't know how many data records there will be. Our web page and the HTML table in it have to adapt dynamically. The following recipe describes how to do this.
Look at the html_table
application. The web page contains two <table>
tags:
<table id="data"></table> <table id="jobdata"></table>
On running the app, you will be redirected to the following web page, which displays data in an HTML table:
The data is shown by the code in the html_table.dart
file.
Job
to insert some real data:TableElement table; TableRowElement row; TableCellElement cell; List<Job> jobs; class Job { String type; int salary; String company; Job(this.type, this.salary, this.company); }
The first table is shown with the preceding code.
table = querySelector('#data'),
row = table.insertRow(0);
0
, assign that cell to a variable, and provide it with content, as shown in the following code:cell = row.insertCell(0); cell.text = 'cell 0-0';
row.insertCell(1) ..text = 'cell 0-1' ..style.background = 'lime'; row.insertCell(2) ..text = 'cell 0-2' ..style.background = 'red';
row = table.insertRow(-1);
row.insertCell(0).text = 'cell 1-0';
Here is the code to display data from a List, applying the same methods as above:
var job1 = new Job("Software Developer", 7500, "Julia Computing LLC") ;
var job2 = new Job("Web Developer", 6500, "Dart Unlimited") ;
var job3 = new Job("Project Manager", 10500, "Project Consulting Inc.") ;
jobs = new List<Job>();
jobs
..add(job1)
..add(job2)
..add(job3);
table = querySelector('#jobdata'),
// insert table headers:
InsertHeaders();
// inserting data:
InsertData();
InsertHeaders() {
row = table.insertRow(-1);
cell = row.insertCell(0);
cell.text = "Jobtype";
cell.style.background = 'lightblue';
cell = row.insertCell(1);
cell.text = "Salary";
cell = row.insertCell(2);
cell.text = "Company";
cell.style.background = 'lightblue';
}
InsertData() {
for (var job in jobs) {
row = table.insertRow(-1);
cell = row.insertCell(0);
cell.text = job.type;
cell = row.insertCell(1);
cell.text = (job.salary).toString();
cell = row.insertCell(2);
cell.text = job.company;
}
}
print(table.rows[1].cells[1].text); // prints 7500
We use the methods insertRow()
and insertCell()
from TableElement
and TableRowElement
, respectively, and the properties of TableCellElement
. Rows and columns are numbered from 0. As shown in the last line of the code, the content of specific cells can be retrieved by using an indexer []
on a specific row and cell.