Snippet: dart_tables Index

Working with <table> elements in Dart

Much like with my java_osx snippet, I haven't found any good and up-to-date guides online that cover this topic, so here I am writing one.

Find more information on Dart here.

For the sake of simplicity I will not be using Dart's cascade feature in my code.

Introduction to Tables in Dart

These are the classes you'll have to work with:

You should never have to instantiate TableSectionElements, TableRowElements or TableCellElements yourself:

Creating a table

TableElement table = new TableElement();

Creating a thead

TableSectionElement tHead = table.createTHead();

Setting thead Column Titles

TableRowElement tHeadRow = tHead.insertRow(0);
Element column1Title = new Element.tag("th");
column1Title.text = "Column 1";
tHeadRow.nodes.add(column1Title);

You'll notice I'm manually creating and adding the th element, this is because Dart doesn't appear to support th elements. An issue has been opened regarding this but has been closed with no real solution.

Creating a tbody

TableSectionElement tBody = table.createTBody();

Adding Rows

TableRowElement tRow = tBody.insertRow(0);

Adding Cells

TableCellElement tCell = tRow.insertCell(0);
tCell.text = "Cell data";

Creating a tfoot

TableSectionElement tFoot = table.createTFoot();

Add rows and data to it normally with insertRow and insertCell.

Full Code

TableElement table = new TableElement();

TableSectionElement tHead = table.createTHead();

TableRowElement tHeadRow = tHead.insertRow(0);

Element column1Title = new Element.tag("th");
column1Title.text = "Column 1";
tHeadRow.nodes.add(column1Title);

Element column2Title = new Element.tag("th");
column2Title.text = "Column 2";
tHeadRow.nodes.add(column2Title);

TableSectionElement tBody = table.createTBody();

TableRowElement tBodyRow1 = tBody.insertRow(0);

TableCellElement tBodyRow1Cell1 = tBodyRow1.insertCell(0);
tBodyRow1Cell1.text = "Cell 1";

TableCellElement tBodyRow1Cell2 = tBodyRow1.insertCell(1);
tBodyRow1Cell2.text = "Cell 2";

TableSectionElement tFoot = table.createTFoot();

TableRowElement tFootRow = tFoot.insertRow(0);

TableCellElement column1Foot = tFootRow.insertCell(0);
column1Foot.text = "Column 1";

TableCellElement column2Foot = tFootRow.insertCell(1);
column2Foot.text = "Column 2";

Will produce:

<table>
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <td>Column 1</td>
            <td>Column 2</td>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
        </tr>
    </tbody>
</table>

Document Changelog

Share: circlefacebook circletwitterbird circlegoogleplus circlereddit