Joe Cox
Joe Cox

Reputation: 11

Using StreamBuilder to build widget from a Future in Flutter

I am trying to build a widget with a list of values returned by an api call using StreamBuilder. The stream is created from a Future using the fromFuture method. I can see the api call being made and a value being placed into the Future variable but the creation of the stream never triggers the StreamBuilder.

Clearly I am missing something with my understanding of streams and how they work in Dart. If anyone could clarify it would be greatly appreciated.

Stateless widget:

return StreamBuilder<List<Category>>(
  stream: api.getCategories(),
  builder: (context, snapshot) {
    if ( snapshot.hasData ) {
      final children = snapshot.data!.map((category) => Text(category.name)).toList();
      return ListView(children: children);
    }
    return Center(child: CircularProgressIndicator());
  },
);

API class:

  Stream<List<Category>> getCategories() {
    return Stream.fromFuture(this.apiCategories());
  }


  Future<List<Category>> apiCategories() async {
      // api call made here
  }

Upvotes: 1

Views: 1890

Answers (1)

Han Parlak
Han Parlak

Reputation: 777

Assuming that you've used await in your future and everything, you could first check if your connection is done or awaiting.

return StreamBuilder<List<Category>>(
  stream: api.getCategories(),
  builder: (context, snapshot) {
    if(snapshot.connectionState == ConnectionState.done){
      if ( snapshot.hasData ) {
        final children = snapshot.data!.map((category) => Text(category.name)).toList();
        return ListView(children: children);
      }
      else{
        return Center(child: Text("No data returned from the API"));
      }
    }
    return Center(child: CircularProgressIndicator());
  },
);

Upvotes: 2

Related Questions