How to use StreamBuildver in Flutter?

205

In this article, we will discuss about how to use StreamBuilder in flutter. We will discuss step by step through example.

StreamBuilder is a widget that builds itself based on the latest snapshot of interaction with a stream.

Constructor of StreamBuilder

(new) StreamBuilder<String> StreamBuilder({
  Key? key,
  String? initialData,
  Stream<String>? stream,
  required Widget Function(BuildContext, AsyncSnapshot<String>) builder,
})

Main Properties:

  • builder: The build strategy currently used by this builder.
  • stream: The asynchronous computation to which this builder is currently connected, possibly null. When changed, the current summary is updated.

Code Implementation

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final bool running = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("StreamBuilder Example"),
        centerTitle: true,
        elevation: 0,
      ),
      body: Center(
        child: StreamBuilder(
            stream: _clock(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.active) {
                return Center(
                  child: Text(
                    '${snapshot.data}',
                    style: const TextStyle(
                        fontSize: 30.0,
                        color: Colors.amber,
                        fontWeight: FontWeight.bold),
                  ),
                );
              }
              return const CircularProgressIndicator();
            }),
      ),
    );
  }

  Stream<String> _clock() async* {
    while (running) {
      await Future<void>.delayed(const Duration(seconds: 1));
      DateTime _now = DateTime.now();
      yield "${_now.year}/${_now.month}/${_now.day} ${_now.hour}:${_now.hour}:${_now.second}";
    }
  }
}

Output:

Thank you for reading this article. If you have any queries regarding any topic, feel free to share with us. We will try to solve your problems.

Happy Learning.

Leave A Reply

Your email address will not be published.