cover-img

Exploring StreamBuilder in Flutter: Building Reactive UIs

Enhancing Real-Time Data Handling with StreamBuilder

10 June, 2023

0

0

0

Introduction

In modern app development, real-time data has become increasingly prevalent. To efficiently handle and display such dynamic information, Flutter provides the StreamBuilder widget. StreamBuilder is a powerful tool that allows developers to build reactive user interfaces that automatically update as new data streams in. In this blog post, we will delve into the world of StreamBuilder and explore how it can elevate your Flutter app's responsiveness.

Understanding StreamBuilder

StreamBuilder is a widget provided by Flutter that takes a stream as input and rebuilds its child tree whenever new data is emitted from the stream. It effectively separates the UI layer from the data layer, allowing for a clear separation of concerns and enabling real-time updates without excessive manual intervention.

Example Usage:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:liquid_swipe/liquid_swipe.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Stream Builder Demo',
      debugShowCheckedModeBanner: false,
      home: StreamBuilderDemo(),
    );
  }
}

class StreamBuilderDemo extends StatefulWidget {
  const StreamBuilderDemo({super.key});

  @override
  State<StreamBuilderDemo> createState() => _StreamBuilderDemoState();
}

class _StreamBuilderDemoState extends State<StreamBuilderDemo> {
  late StreamController<int> _streamController;

  @override
  void initState() {
    _streamController = StreamController<int>();

    super.initState();
    Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        _streamController.sink.add(timer.tick);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('StreamBuilderDemo Example'),
      ),
      body: Center(
        child: StreamBuilder<int>(
          stream: _streamController.stream,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text(
                'Current number: ${snapshot.data}',
                style: TextStyle(fontSize: 24),
              );
            } else {
              return CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }
}

This code demonstrates the usage of the StreamBuilder widget in Flutter. Let's go through it step by step:

  1. The code starts with the standard main() function, where the MyApp widget is instantiated and run.
  2. MyApp is a stateless widget that serves as the root of the application. It sets the title and the home screen as an instance of the StreamBuilderDemo widget.
  3. StreamBuilderDemo is a stateful widget that extends State<StreamBuilderDemo>. It represents the main widget where the StreamBuilder is used.
  4. Inside the _StreamBuilderDemoState class, a StreamController<int> called _streamController is declared. This controller will be used to manage the stream.
  5. In the initState() method, the _streamController is initialized, and a Timer.periodic is used to emit numbers to the stream every second. The setState() function is used to update the UI and trigger a rebuild with the latest number.
  6. The build() method is overridden to create the UI. It displays an AppBar and a Center widget containing the StreamBuilder. The StreamBuilder listens to the stream from _streamController.stream.
  7. Inside the builder function of the StreamBuilder, it checks if the snapshot has data. If data is available, it displays the current number using a Text widget. If no data is available, it shows a CircularProgressIndicator to indicate that data is still loading.
  8. The dispose() method is overridden to properly close the _streamController when the widget is disposed to avoid memory leaks.

Overall, this code sets up a StreamBuilder that listens to a stream created by a StreamController. The stream emits numbers every second, and the UI automatically updates to display the latest number in real-time.

Output

Here's the output of the above code 👇

Stream Builder Output

Conclusion

StreamBuilder is an essential widget in the Flutter framework that enables the creation of reactive user interfaces by automatically updating the UI in response to data streams. By harnessing the power of streams, developers can effortlessly handle real-time data updates and provide users with a seamless experience. With its intuitive usage and flexibility, StreamBuilder is an invaluable tool for building dynamic and responsive Flutter applications.

Incorporating StreamBuilder into your projects empowers you to build robust, real-time features that keep your app's content fresh and engaging. So why not leverage StreamBuilder to handle dynamic data streams and provide your users with an immersive and up-to-date experience in your Flutter applications?

For more amazing readings, follow me on Showwcase and Twitter 😃

flutter

developer

ui

statemanagement

app

0

0

0

flutter

developer

ui

statemanagement

app

Hasnain Makada
Elite @Showwcase | Prev: CCO @ShowwcaseHQ | Building out OSWH 👨‍💻 | MLSA - β | DevOps and Flutter 💙 | Blogger at Hashnode and Showwcase 📑

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.