How to fill a DataTable using StreamBuilder in Flutter

In this flutter code example, we will see how to use a StreamBuilder to fill a DataTable in flutter.

This is some information from flutter developer’s guide that will help us understand flutter data table.

Displaying data in a table is expensive, because to lay out the table all the data must be measured twice, once to negotiate the dimensions to use for each column, and once to actually lay out the table given the results of the negotiation.
For this reason, if you have a lot of data (say, more than a dozen rows with a dozen columns, though the precise limits depend on the target device), it is suggested that you use a PaginatedDataTable which automatically splits the data into multiple pages

With the above explanation we will go further to use a simple code to show an example of flutter DataTable using StreamBuilder.

CREATE NEW FLUTTER PROJECT

In your Visual Studio Code, go to View menu > Command Palette.

In the open dialog, select Flutter. Enter the name of your Flutter project and hit enter key button.

Right click on the lib folder and create a new dart file inside the folder.

Feel free to use a name of our choice. For the purpose of this example I will name my dart file – datatable_with_streambuilder.dart.

Open the file and add the code below.

import 'dart:async';

import 'package:flutter/material.dart';

class DataTableInStreamBuilder extends StatelessWidget {
  Stream<int> timedCounter(Duration interval, [int maxCount]) async* {
    int i = 0;
    while (true) {
      await Future.delayed(interval);
      yield i++;
      if (i == maxCount) break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("DataTable in StreamBuilder")),
      body: StreamBuilder<int>(
        stream: timedCounter(Duration(seconds: 2), 10),
        //print an integer every 2secs, 10 times
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Text("Loading");
          }
          int count = snapshot.data;
          return DataTable(
            rows: [
              DataRow(
                cells: [
                  DataCell(Text("${count + 1}")),
                  DataCell(Text("${count + 2}")),
                  DataCell(Text("${count + 3}")),
                ],
              ),
              DataRow(
                cells: [
                  DataCell(Text("${count + 4}")),
                  DataCell(Text("${count + 5}")),
                  DataCell(Text("${count + 5}")),
                ],
              ),
              DataRow(
                cells: [
                  DataCell(Text("${count + 6}")),
                  DataCell(Text("${count + 7}")),
                  DataCell(Text("${count + 8}")),
                ],
              ),
            ],
            columns: [
              DataColumn(
                label: Text("From 1"),
              ),
              DataColumn(
                label: Text("From 4"),
              ),
              DataColumn(
                label: Text("From 6"),
              ),
            ],
          );
        },
      ),
    );
  }
}

OPEN MAIN.DART FILE

Open the default main.dart file located inside the lib folder.

We need to import datatable_with_streambuilder.dart at the top of the page.

Assign an instance of the DataTableInStreamBuilder class to the MaterialApp home attribute.

import 'package:flutter/material.dart';
import 'datatable_with_streambuilder.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: DataTableInStreamBuilder(),
    );
  }
}

RUN YOUR APP

You can use flutter command to run your app – $ flutter run

If everything goes well, you will see screen similar to the image below in your flutter device.

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment