Skip to main content

Command Palette

Search for a command to run...

StreamBuilder widget and Attributes

Published
2 min read
StreamBuilder widget and Attributes
V

"Hello World, I'm Vinit Mepani, a coding virtuoso driven by passion, fueled by curiosity, and always poised to conquer challenges. Picture me as a digital explorer, navigating through the vast realms of code, forever in pursuit of innovation.

In the enchanting kingdom of algorithms and syntax, I wield my keyboard as a magical wand, casting spells of logic and crafting solutions to digital enigmas. With each line of code, I embark on an odyssey of learning, embracing the ever-evolving landscape of technology.

Eager to decode the secrets of the programming universe, I see challenges not as obstacles but as thrilling quests, opportunities to push boundaries and uncover new dimensions in the realm of possibilities.

In this symphony of zeros and ones, I am Vinit Mepani, a coder by passion, an adventurer in the digital wilderness, and a seeker of knowledge in the enchanting world of code. Join me on this quest, and let's create digital wonders together!"

The StreamBuilder widget in Flutter is used to build UI components based on the latest snapshot of data from a stream. It's commonly used for asynchronous operations such as fetching data from APIs or handling user input events.

Attributes:

  1. stream (Stream<T>):

    • The stream of data to listen to. The UI will be rebuilt whenever new data is emitted from the stream.
  2. builder (Widget Function(BuildContext, AsyncSnapshot<T>)):

    • A builder function that returns a widget tree based on the latest snapshot of data from the stream. It takes two arguments: the BuildContext and an AsyncSnapshot object containing the latest data from the stream.

Example:

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

class StreamBuilderExample extends StatefulWidget {
  @override
  _StreamBuilderExampleState createState() => _StreamBuilderExampleState();
}

class _StreamBuilderExampleState extends State<StreamBuilderExample> {
  StreamController<int> _streamController = StreamController<int>();
  int _counter = 0;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('StreamBuilder Widget Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            StreamBuilder<int>(
              stream: _streamController.stream,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return CircularProgressIndicator();
                } else if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                } else {
                  return Text('Counter: ${snapshot.data}');
                }
              },
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                _counter++;
                _streamController.add(_counter);
              },
              child: Text('Increment Counter'),
            ),
          ],
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: StreamBuilderExample(),
  ));
}

Explanation:

  • In this example, a StreamBuilder widget is used to display the current value of a counter, which is incremented each time a button is pressed.

  • A StreamController is used to create a stream of integers (int).

  • Inside the build method, the StreamBuilder widget listens to changes in the stream of integers and rebuilds the UI accordingly.

  • The builder function inside the StreamBuilder is called whenever new data is emitted from the stream. It checks the ConnectionState of the snapshot and returns different UI components based on the current state.

  • If the connection state is ConnectionState.waiting, a CircularProgressIndicator is displayed to indicate that data is being loaded.

  • If there's an error in the stream, an error message is displayed.

  • Otherwise, the current value of the counter is displayed using a Text widget.

  • When the button is pressed, the counter is incremented and the new value is added to the stream using _streamController.add(_counter).

  • As a result, the UI is updated automatically to reflect the latest value of the counter.

More from this blog

Vinit Mepani (Flutter Developer)

270 posts

"Vinit Mepani, passionate coder! Dive into my Dart and Flutter journey on the blog. Let's master these tech wonders together. Happy coding! 🚀"