What is Difference Between StreamBuilder and FutureBuilder In Flutter ?

· 5 min read
What is StreamBuilder and FutureBuilder In Flutter
What is StreamBuilder and FutureBuilder In Flutter

FutureBuilder calls the future function to wait for the result, and as soon as it produces the result it calls the builder function where we build the widget. So in this article, we will go through What is StreamBuilder and FutureBuilder In Flutter?

What are StreamBuilder and FutureBuilder In Flutter?

Both StreamBuilder and FutureBuilder have the same behavior: They listen to changes on their respective object. And trigger a new build when they are notified of a new value.

So in the end, their differences are how the object they listen to works.

Future is like Promise in JS or Task in c#. They are the representation of an asynchronous request. Futures have one and only one response. A common usage of Future is to handle HTTP calls. What you can listen to on a Future is its state whether it’s done, finished with success, or had an error. But that’s it.

Stream on the other hand is like async Iterator in JS. It is assimilated to a value that changes over time. It usually is the representation of web sockets or events such as clicks. By listening to a Stream you’ll get each new value and also if the Stream had an error or completed.

A Future can’t listen to a variable change. It’s a one-time response. Instead, you’ll need to use a Stream.

FutureBuilder is used for one-time responses, like taking an image from Camera, getting data once from the native platform like fetching device battery, getting file reference, making an HTTP request, etc.

On the other hand, StreamBuilder fetches some data more than once, like listening for location updates, playing music, stopwatch, etc.

Here is a full example mentioning both cases.

FutureBuilder solves a square value and returns the result after 5 seconds, till then we show a progress indicator to the user.

StreamBuilder shows a stopwatch, incrementing _count value by 1 every second.

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _count = 0; // used by StreamBuilder

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _buildFutureBuilder(),
          SizedBox(height: 24),
          _buildStreamBuilder(),
        ],
      ),
    );
  }

  // constructing FutureBuilder
  Widget _buildFutureBuilder() {
    return Center(
      child: FutureBuilder<int>(
        future: _calculateSquare(10),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done)
            return Text("Square = ${snapshot.data}");

          return CircularProgressIndicator();
        },
      ),
    );
  }

  // used by FutureBuilder
  Future<int> _calculateSquare(int num) async {
    await Future.delayed(Duration(seconds: 5));
    return num * num;
  }

  // constructing StreamBuilder
  Widget _buildStreamBuilder() {
    return Center(
      child: StreamBuilder<int>(
        stream: _stopwatch(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.active)
            return Text("Stopwatch = ${snapshot.data}");

          return CircularProgressIndicator();
        },
      ),
    );
  }

  // used by StreamBuilder
  Stream<int> _stopwatch() async* {
    while (true) {
      await Future.delayed(Duration(seconds: 1));
      yield _count++;
    }
  }
}

A Future is like a token with a number on it that they give you when you order takeout; you made the request, but the result is not yet ready but you have a placeholder. And when the result is ready, you get a callback the digital board above the takeout counter shows your number or they shout it out – you can now go in and grab your food the result to take out.

A Stream is like that belt carrying little sushi bowls. By sitting down at that table, you’ve “subscribed” to the stream. You don’t know when the next sushi boat will arrive – but when the chef message source places it in the stream (belt), then the subscribers will receive it. The important thing to note is that they arrive asynchronously you have no idea when the next boat/message will come but they will arrive in sequence (i.e., if the chef puts three types of sushi on the belt, in some order — you will see them come by you in that same order

Conclusion:

In this article, we have been through What is FutureBuilder and When to use FutureBuilder?

Thanks for being with us!!!
Keep Learning, Keep Fluttering !!!

Do let us know if you need any assistance with Flutter Development.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply