StreamBuilder widget and Attributes

StreamBuilder widget and Attributes

ยท

2 min read

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.

Did you find this article valuable?

Support Vinit Mepani by becoming a sponsor. Any amount is appreciated!

ย