首页 > 解决方案 > 带有列表的 Flutter Futurebuilder 不起作用

问题描述

我有一个带有 Future 函数的 Futurebuilder,它返回一个包含来自 Firebase 存储的图像 url 的列表。

  child: FutureBuilder(
    future: getImages(),
    builder: (context, AsyncSnapshot snapshot) {
      //print(snapshot.data);
      if (snapshot.connectionState == ConnectionState.done) {
        print(snapshot.data[0]);
        return ListView.builder(
            shrinkWrap: true,
            itemCount: 2,//snapshot.data.length,
            itemBuilder: (BuildContext context, int index) {
              //var downloadUrl = snapshot.data[index];
              return ListTile(
                contentPadding: EdgeInsets.all(8.0),
                 leading: Image.network(
                     //downloadUrl
                    "https://placehold.it/500x500"
                     , fit: BoxFit.fill),
              );
            });
      } else if (snapshot.connectionState == ConnectionState.none) {
        return Text("No data");
      }
      return CircularProgressIndicator();
    },
  ),
  Future<List<String>> getImages() async{
    var showcaseCode = await page.where("userID",isEqualTo:
    FirebaseAuth.instance.currentUser.uid).get();
    List downloadUrlList = [];
    var showcaseCodeLength = showcaseCode.docs.length;
    for(var i = 0; i < showcaseCodeLength; i++){
      var url = await FirebaseStorage.instance.ref()
          .child("showcase_images")
          .child(showcaseCode.docs[i]["showcaseCode"])
          .getDownloadURL();
      await downloadUrlList.add(url);
    }
    print(downloadUrlList);
    return downloadUrlList;
  }

当我downloadUrlListgetImages未来打印时,我的 url 列表有正确的输出。但如果我downloadUrlList 在 Futurebuilder 中打印,我会收到以下错误:

The method '[]' was called on null. 
Receiver: null 
Tried calling: [](0)

谢谢你的帮助!

标签: firebasefluttergoogle-cloud-firestoreerror-handling

解决方案


要在这个问题上有答案:

正如@pskink 评论,使用以下代码解决了这个问题:

List downloadUrlList = <String>[]

或者

List<String> downloadUrlList = []


推荐阅读