我想将ListView转换为CustomScrollView,所以我需要将FutureBuilder转换为SliverList

这是我的代码:

class LatestNewsList extends StatefulWidget {
  @override
  _LatestNewsListState createState() => _LatestNewsListState();
}

class _LatestNewsListState extends State<LatestNewsList> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Data>>(
      future: getQuake(),
      builder: (context, snapshot){
        if(snapshot.hasError) print(snapshot.error);

        return snapshot.hasData
            ? NewsList(latestNews: snapshot.data,)
            : Center(child: CircularProgressIndicator());
      },
    );
  }
}

class NewsList extends StatelessWidget {
  final List<Data> latestNews;

  NewsList({this.latestNews});

  @override
  Widget build(BuildContext context) {



    return new ListView.builder(
        itemCount: latestNews.length,
        itemBuilder: (context, index){
          return new GestureDetector(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => Browser(url: latestNews[index].post_link,)
                  )
              );
            },
            child: new LatestNewsItem(
              post_title: latestNews[index].post_title,
              post_link: latestNews[index].post_link,
              img_src: latestNews[index].img_src,
            ),
          );
        }
    );
  }
}

如何将相同的FutureBuilder逻辑转换为SliverList?

最佳答案

CustomScrollView的子代必须是条状,您不能使用FutureBuilder

相反,在将来完成时重建CustomScrollView:

// build fixed items outside of the FutureBuilder for efficiency
final someOtherSliver = SliverToBoxAdapter(...);

return FutureBuilder<List<Data>>(
  future: getQuake(), // this is a code smell. Make sure that the future is NOT recreated when build is called. Create the future in initState instead.
  builder: (context, snapshot){
    Widget newsListSliver;
    if(snapshot.hasData) {
      newsListSliver = SliverList(delegate: SliverChildBuilderDelegate(...))
    } else {
      newsListSliver = SliverToBoxAdapter(child: CircularProgressIndicator(),);
    }

    return CustomScrollView(
      slivers: <Widget>[
        someOtherSliver,
        newsListSliver
      ],
    );
  },
);

如果您有多个依赖于FutureStream的条,则可以链接构建器:
return FutureBuilder<..>(
  ...
  builder: (context, snapshot1) {
    return FutureBuilder<..>(
      ...
      builder: (context, snapshot2) {
        return CustomScrollView(...);
      }
    )
  }
)

关于flutter - 如何在SliverList中使用FutureBuilder,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52146850/

10-12 05:20