Flutter StreamBuilder Example Code

In one of my previous flutter code example on how to use StreamBuilder with Firestore in Flutter, we shed some light on what is StreamBuilder in Flutter? When and how to use flutter StreamBuilder?

Here, I will also share an interesting flutter code example that illustrates with code another example on how to use Flutter 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 – streambuilder_example_code.dart.

Open the file and add the code below.

import 'dart:async';

import 'package:flutter/material.dart';

class UsingStreamBuilder 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("StreamBuilder in Flutter")),
      body: Center(
        child: StreamBuilder<int>(
          stream: timedCounter(Duration(seconds: 2), 10),
          //print an integer every 2secs, 10 times
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Text("No data");
            }
            return Text("${snapshot.data.toString()}",
                style: TextStyle(fontSize: 20));
          },
        ),
      ),
    );
  }
}

Open main.dart file

To run our simple flutter Streambuilder example, we will need to import this file to our project main.dart file and assign an instance of UsingStreamBuilder class as the value of the MaterialApp widget home attribute.

import 'package:flutter/material.dart';
import 'streambuilder_example_code.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: UsingStreamBuilder(),
    );
  }
}

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