Sobes.tech
Junior — Middle

How do StreamBuilder and Future components differ when working with asynchronous data in Flutter?

sobes.tech AI

Answer from AI

In Flutter, FutureBuilder and StreamBuilder are used for working with asynchronous data, but they differ in the type of data source:

  • FutureBuilder works with a Future object — a one-time asynchronous operation that returns a result or an error once. For example, loading data from a server.

  • StreamBuilder works with a Stream — a data flow that can emit multiple events over time. For example, real-time data updates or user input events.

Example of using FutureBuilder:

FutureBuilder<String>(
  future: fetchData(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return CircularProgressIndicator();
    } else if (snapshot.hasError) {
      return Text('Error: \\${snapshot.error}');
    } else {
      return Text('Data: \\${snapshot.data}');
    }
  },
)

Example of using StreamBuilder:

StreamBuilder<int>(
  stream: counterStream(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return CircularProgressIndicator();
    }
    return Text('Counter: \\${snapshot.data}');
  },
)

Thus, choose FutureBuilder for one-time operations and StreamBuilder for streaming data.

How do StreamBuilder and Future components differ… - sobes.tech