A StreamBuilder alternative that provides builder and event callbacks

Overview

mainstream

A StreamBuilder alternative that provides builder and event callbacks.

See the Futuristic package for a similar API for working with Futures.

Problem

StreamBuilder is one of the most powerful widgets in Flutter. Like AnimatedBuilder and ValueListenableBuilder, it can be used to selectively rebuild only parts of a widget, which is very efficient.

However StreamBuilder does not provide a way to receive callbacks for a Stream's data/error/done events. Often we may want to respond to those events by performing an action. For example, updating a Navigator. Doing this from inside the builder callback is unreliable because Flutter can call the build() method many times. So we need an additional stream listener. However this requires the boilerplate of creating a StatefulWidget and canceling our stream subscription. Also, if our stream is not a broadcast stream (meaning it supports multiple listeners), we might have to avoid using a StreamBuilder altogether.

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  StreamSubscription<FirebaseUser> _subscription;

  @override
  void initState() {
    super.initState();
    _subscription = FirebaseAuth.instance.onAuthStateChanged.listen((event) {
      Navigator.of(context).popUntil((route) => route.isFirst);
    });
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<FirebaseUser>(
      stream: FirebaseAuth.instance.onAuthStateChanged,
      builder: (_context, snapshot) => snapshot.data.isAnonymous ? LoggedOut() : LoggedIn(),
    );
  }
}

Solution

The MainStream widget uses the same underlying StreamBuilderBase used by StreamBuilder but also exposes additional onData/onError/onDone callbacks. These callbacks will not retriggered as the result of a widget rebuild. It also provides builder callbacks to build mutually exclusive busy/data/error widget states.

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MainStream<FirebaseUser>(
      stream: FirebaseAuth.instance.onAuthStateChanged,
      onData: (_) => Navigator.of(context).popUntil((r) => r.isFirst),
      dataBuilder: (_, data) => data.isAnonymous ? LoggedOut() : LoggedIn(),
    );
  }
}
  • Can be used in a StatelessWidget
  • Works with single-subscription and broadcast streams
  • Provides generic type safety for the data provided to callbacks. The type parameter <T> can be omitted if it can be inferred by the compiler.

Usage

final myStream = Stream<int>.periodic(Duration(seconds: 1), (x) => x).take(5);

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MainStream<int>(
      stream: myStream,
      onData: (data) => print(data),
      onError: (error) => showDialog(...),
      onDone: () => print('Done!'),
      busyBuilder: (_) => CircularProgressIndicator(),
      dataBuilder: (_, data) => Text(data.toString()),
      errorBuilder: (_, error) => Text(error.toString()),
    );
  }

The stream parameter is required.

The optional busyBuilder displays a widget when the Stream is waiting for its first event. By default, it shows a centered CircularProgressIndicator.

The optional dataBuilder displays a widget when the Stream's last event it a succesful data payload. The resulting T value of the Stream<T> is provided as a parameter to the callback.

The optional errorBuilder displays a widget when the Stream last event is an error, typically an Error or Exception.

The optional onData callback can be used to handle a successful data event by displaying an alert dialog or performing navigation, for example. This can be used in place of or together with the dataBuilder. This will not be retriggered as a result of a widget rebuild.

The optional onError callback can be used to handle an error event by displaying an alert dialog or sending to a logging provider, for example. It can be used in place of or together with the errorBuilder. This will not be retriggered as a result of a widget rebuild.

The optional onDone callback can be used to handle a Stream's done event. This will not be retriggered as a result of a widget rebuild.

You might also like...

An Advanced Logging Framework develop in flutter that provides quick & simple logging solution.

An Advanced Logging Framework develop in flutter that provides quick & simple logging solution.

FLogs Advance Logging Framework FLog is an Advanced Logging Framework develop in flutter that provides quick & simple logging solution. All logs are s

Dec 30, 2022

FileManager is a wonderful widget that allows you to manage files and folders, pick files and folders, and do a lot more. Designed to feel like part of the Flutter framework.

FileManager is a wonderful widget that allows you to manage files and folders, pick files and folders, and do a lot more. Designed to feel like part of the Flutter framework.

File Manager FileManager is a wonderful widget that allows you to manage files and folders, pick files and folders, and do a lot more. Designed to fee

Dec 30, 2022

Flutter ShopApp, you can see products and their prices, categories and their products, search for a product, add to favorite, add to cart, sign in and sign up.

shop_app_2 A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to get you started i

Aug 7, 2022

A mobile image uploader in which you can upload image to your personal gallery from either your camera or mobile gallery and it can detect your current geographic location and address using firebase firestore and storage.

Image Uploader In Flutter About It is an Image Uploader gallery which tracks your address from which you're uploading using Flutter and Image picker.

Dec 20, 2022

A Flutter plugin for handling Connectivity and REAL Connection state in the mobile, web and desktop platforms. Supports iOS, Android, Web, Windows, Linux and macOS.

A Flutter plugin for handling Connectivity and REAL Connection state in the mobile, web and desktop platforms. Supports iOS, Android, Web, Windows, Linux and macOS.

cross_connectivity A Flutter plugin for handling Connectivity and REAL Connection state in the mobile, web and desktop platforms. Supports iOS, Androi

Nov 15, 2022

Developed a Group chat application using Flutter and Firebase, where users can register and create groups or join already existing groups and start conversing with each other.

Developed a Group chat application using Flutter and Firebase, where users can register and create groups or join already existing groups and start conversing with each other.

GroupChatApp About Developed a Group chat application using Flutter and Firebase, where users can register and create groups or join already existing

Dec 1, 2022

This is a shop-app you can see the products and With prices and knowing if there are discounts and adding your favorite products to the favorite products page

This is a shop-app you can see the products and With prices and knowing if there are discounts and adding your favorite products to the favorite products page, you can search for a specific product and also modify personal information from the settings , I made it using REST APIs by using (Dio packedge) , (shared Preference) and state management (Bloc/cubit

Oct 27, 2022

E-Studying-V1 - Flutter application where you can download files from an api and unarchive them and open them and see their contents

E-Studying-V1 - Flutter application where you can download files from an api and unarchive them and open them and see their contents

E-Studying-V1 - Flutter application where you can download files from an api and unarchive them and open them and see their contents

Jan 20, 2022
Owner
Martin Rybak
Martin Rybak
An android app built using flutter that displays and forecast the specific city Weather and Climate for dynamic time event by collecting the data from API that is provided for free by OPENWEATHER site.

clima_weather_reporter A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to get y

dev_allauddin 3 Feb 3, 2022
An open source shazam alternative built using Flutter

bazinga An open source shazam alternative Getting Started This project is a starting point for a Flutter application. A few resources to get you start

Daniel Dennis 3 Aug 27, 2022
An alternative front-end to GoogleTranslate

SimplyTranslate Mobile (Unofficial) An alternative front-end to GoogleTranslate Download Via F-Droid: com.simplytranslate_mobile. For the most up-to-d

null 101 Dec 28, 2022
An event management system.

?? Eventour ?? ?? The GOTO event management app. ⭐ What was our motivation? As technology advances, we often aim for newer and better approaches for s

Eshan Gupta 4 Jan 27, 2022
For flutter native plugins, send event to main thread.

native_main_thread A new Flutter plugin. Getting Started This project is a starting point for a Flutter plug-in package, a specialized package that in

null 0 Nov 26, 2021
Allows Dart reflection using code generation/builder.

reflection_factory reflection_factory allows Dart reflection with an easy approach, even for third-party classes, using code generation portable for a

Graciliano Monteiro Passos 13 Oct 30, 2022
The FlexGrid control provides a powerful and quickly way to display data in a tabular format. It is including that frozened column/row,loading more, high performance and better experience in TabBarView/PageView.

flex_grid Language: English| 中文简体 The FlexGrid control provides a powerful and quickly way to display data in a tabular format. It is including that f

FlutterCandies 39 Nov 8, 2022
Provides a complete list of Philippine towns, cities, provinces and regions.

Philippines This provides a complete list of Philippine towns, cities, provinces and regions. References: http://en.wikipedia.org/wiki/Regions_of_the_

Roy Evan Sia 64 Oct 3, 2022
Movie Lib is a mobile application where you can find the movies of your interest. This app provides a collection of movies of different languages according to your interest.

Movie Lib Movie Lib is a mobile application where you can find the movies of your interest. This app provides a collection of movies of different lang

Abhijith Kp 6 Sep 28, 2021
cosmic_frontmatter is a package that provides a simple way to parse the frontmatter of a markdown file.

cosmic_frontmatter cosmic_frontmatter is a package that provides a simple way to parse the frontmatter of a markdown file. Getting started To get star

cosmic.horse 9 Oct 26, 2022