FutureBuilder and StreamBuilder in Flutter

yohanym95

Yohan Malshika

Posted on June 9, 2021

FutureBuilder and StreamBuilder in Flutter

Hi All, Hope you are all doing well. Today I am planning to tell you about FutureBuilder and StreamBuilder widgets in Flutter.

In this article, I will tell you,

  • FutureBuilder widget
  • How to use FutureBuilder Widget
  • StreamBuilder widget
  • How to use StreamBuilder Widget
  • Difference between FutureBuilder and StreamBuilder

Let’s get started!

What is the FutureBuilder widget in Flutter?

FutureBuilder is a widget that uses Future operations which easily determine the current state of the Future and you can choose what to show when the data is loading and when it is available.

How to use the FutureBuilder widget?

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

class FutureBuilderTest extends StatefulWidget {
  @override
  _FutureBuilderTestState createState() => _FutureBuilderTestState();
}

class _FutureBuilderTestState extends State<FutureBuilderTest> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter 101'),
      ),
      body: Container(
        child: FutureBuilder(
          future:
              FirebaseDatabase.instance.reference().child("Examples").once(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Example(snapshot.data);
            }else{
              return CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

You can see the above example for the FutureBuilder widget. In that example, I retrieve data from the firebase real-time database and by using the FutureBuilder Widget. Because it uses the Future operation.

FutureBuilder requires 2 parameters,

future: A method that returns a future object

builder: widgets that will be returned during different states of a future builder.

As well as there is another parameter called the initialData. we can use it as a default value until and unless we get the value from the future.

Also, you can see we can load any widget while loading the data, and also we can handle load any widget or handle it when the snapshot has any error by using the snapshot.hasError.

if (snapshot.connectionState == ConnectionState.done) {
  if(snapshot.hasError){
     return SomethingWentWrong();
   }
}
Enter fullscreen mode Exit fullscreen mode

What is the StreamBuilder widget in Flutter?

StreamBuilder is a widget that uses stream operations and basically, it rebuilds its UI when it gets the new values that are passed via Stream it listens to.

How to use StreamBuilder widget in flutter?

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

class StreamBuilderTest extends StatefulWidget {
  @override
  _StreamBuilderTestState createState() => _StreamBuilderTestState();
}

class _StreamBuilderTestState extends State<StreamBuilderTest> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter 101'),
      ),
      body: Container(
        child: StreamBuilder(
          stream: FirebaseDatabase.instance
              .reference()
              .child("Examples")
              .once()
              .asStream(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Example(snapshot.data);
            }else{
              return CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

StreamBuilder requires 2 parameters,

stream: A method that returns a stream object

builder: widgets that will be returned during different states of a streambuilder.

As well as there is another parameter called the initialData like intialData parameter in FutureBuilder. we can use it as a default value until and unless we get the value from the stream.

As I mentioned before, we can load any widget while loading the data, and also we can handle load any widget or handle it when the snapshot has any error by using the snapshot.hasError.

And Also you can see FutureBuilder and StreamBuilder using the AsyncSnapshot. What is that?

AsyncSnapshot is a class that wraps the latest received data from the stream or future objects.

Difference between FutureBuilder and StreamBuilder

Basically, StreamBuilder and FutureBuilder have the same behavior and they listen to changes on their respective object(Future and Stream). But their difference comes with how they listen to async calls.

When we use FutureBuilder, it has only one response. because it uses the Future object and Future has one and only one response. Basically, Future is used to handle HTTP requests. So we listen on a Future is its state. when it’s done or had an error, that’s it.

When we use StreamBuilder, it uses stream object, and stream like a pipe, when you put a value on the one end and if there is a listener on the other hand it will receive the value that you put. It usually is the representation of web-sockets or events (such as click). By listening to a Stream you'll get each new value and also if the Stream had an error or completed.

So That’s it for today. I think you learned something new from my article.

See you again soon with another article !!

Happy Coding 👽!!!

💖 💪 🙅 🚩
yohanym95
Yohan Malshika

Posted on June 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related