How do I use async/HTTP data to return child widgets in an IndexedWidgetBuilder?

Viewed 1919

I'm obtaining JSON data over HTTP and displaying it in a ListView. Since it's HTTP, it's all async.

Here's what I'd like to do:

var index = new ListView.builder(
  controller: _scrollController,
  itemBuilder: (ctx, i) async {
    _log.fine("loading post $i");
    var p = await _posts[i];
    return p == null ? new PostPreview(p) : null;
  },
);

Unfortunately, this doesn't work since IndexedWidgetBuilder has to be a synchronous function. How do I use a Future to build a child for an IndexedWidgetBuilder? It doesn't seem like there's a way to wait for the future to complete synchronously.

Previously, I was loading the data into an array and the IndexedWidgetBuilder function only checked to see if the list elements existed before returning the child widget.

var index = new ListView.builder(
  controller: _scrollController,
  itemBuilder: (ctx, i) {
    _log.fine("loading post $i");
    return _posts.length > i ? new PostPreview(_posts[i]) : null;
  },
);

This works, but I would like to completely separate the view from the data and asynchronously request the JSON as needed.

This also seems, in my limited experience, like it might be a common use-case. Could an async version of IndexWidgetBuilder be added to flutter?

1 Answers
Related