使用 FutureBuilder 创建轮播

Creating Carousel using FutureBuilder

我正在将图像存储在 Firestore 文档中,并想使用 FutureBuilder 加载它们。这是我到目前为止所做的:

     Future getCarouselWidget() async {
        var firestore = Firestore.instance;
        QuerySnapshot qn = await firestore.collection("carousel").getDocuments();
        return qn.documents;
      }

 Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
          future: getCarouselWidget(),
          builder: (context, AsyncSnapshot snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return new CircularProgressIndicator(); 
            } else {
              if (snapshot.hasError) {
                return new Text("fetch error");
              } else {
                return new Container(
                    height: 250.0,
                    child: new Carousel(
                      boxFit: BoxFit.cover,
                      images: [NetworkImage(snapshot.data[0].data["img_2"])],
                      autoplay: false,
                      dotSize: 4.0,
                      indicatorBgPadding: 4.0,
                      animationCurve: Curves.fastOutSlowIn,
                      animationDuration: Duration(milliseconds: 1000),
                    ));
              }
            }
          }),
    );
  }'

使用上面的代码,我可以毫无错误地显示图像。但是,我不知道如何遍历快照数据来显示图像列表。

下面是我的 firestore 结构:

关注这个 youtube 指南 https://www.youtube.com/watch?v=R2I0osLdjgQ https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html

//I assume this function futures a list of images
Future getCarouselWidget() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore.collection("carousel").getDocuments();
    return qn.documents;
  }


Widget build(BuildContext context) {
    return Container(
        child: FutureBuilder(
            future: getCarouselWidget(),
            builder: (context, AsyncSnapshot snapshot) {
                switch( snapshot.connectionState ){
                   case ConnectionState.none:
                      return new Text("Data is not fetched");
                   case ConnectionState.waiting:
                      return new CircularProgressIndicator();
                   case ConnectionState.done:
                      if(snapshot.hasError){
                          return new Text("fetch error")
                      } else {
                         return new Container(
                          height: 250.0,
                          child: new Carousel(
                          boxFit: BoxFit.cover,
                          images: snapshot.data,
                          autoplay: false,
                          dotSize: 4.0,
                          indicatorBgPadding: 4.0,
                          animationCurve: Curves.fastOutSlowIn,
                          animationDuration: Duration(milliseconds: 1000),
                        ));
                      }
                   default:
                      return Text("connection is just active");
                }
            }

编辑:我没有关于 firestore 文档数据类型的任何文档。 不知道下面的代码对不对。

Future getCarouselWidget() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore.collection("carousel").getDocuments();
    // convert DocumentSnapshots to Images.
    // I am assuming Document Snapshots are <String, Images>
    var ret = new List();
    qn.documents.forEach( 
       (v) => 
           for( var e in v.data.values ) {
               ret.add(new NetworkImage(e));
           }
     );
    return ret.map((nI) => new Image(image: nI)).toList();
  }

这就是解决方案。基本上,我遍历文档快照并将结果保存在列表中。然后,我将列表设置为图像。

 Widget build(BuildContext context) {
    var idx = 1;
    return Container(
      child: FutureBuilder(
          future: getCarouselWidget(),
          builder: (context, AsyncSnapshot snapshot) {
            List<NetworkImage> list = new List<NetworkImage>();
            if (snapshot.connectionState == ConnectionState.waiting) {
              return new CircularProgressIndicator(); 
            } else {
              if (snapshot.hasError) {
                return new Text("fetch error");
              } else {

                //Create for loop and store the urls in the list 
                for(int i = 0; i < snapshot.data[0].data.length; i++ ) {
                  debugPrint("Index is " + idx.toString());
                  list.add(NetworkImage(snapshot.data[0].data["img_"+idx.toString()]));
                  idx++;
                }
                return new Container(
                    height: 250.0,
                    child: new Carousel(
                      boxFit: BoxFit.cover,
                      images: list,   <== Set the list here 
                      autoplay: true,
                      dotSize: 4.0,
                      indicatorBgPadding: 4.0,
                      animationCurve: Curves.fastOutSlowIn,
                      animationDuration: Duration(milliseconds: 1000),
                    ));
              }
            }
          }),
    );