如何在项目构建器中显示Firestore中的列表

时间:2019-01-27 06:43:04

标签: dart flutter google-cloud-firestore

下面的getIngredients()方法从firestore返回一个列表。

Future getIngredients() async {
    return Firestore.instance
        .collection('ingredients')
        .where("name", isEqualTo: widget.dish_name.toString().toLowerCase()).getDocuments();
  }

现在,我想在下面的项目构建器中显示此列表:

 new ListView.builder(
                  itemExtent: 90,
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                      return SingleIngredient(
                        ingredient_name: snapshot.data[index].ingredients,
                      );
                  });

我收到以下错误消息:

  

_FutureBuilderState#7cbda):I / flutter(12164):类“ QuerySnapshot”没有实例获取器“ length”。 I /颤振(12164):   接收方:“ QuerySnapshot” I / flutter的实例(12164):已尝试   通话:长度

这是我的消防库的建筑。我正在获取配料表:

enter image description here

更新 我已经更新了代码,但仅从成分列表(即洋葱)中获取了第一项。我想让itembuilder构建列表中的每个项目,因为我试图显示图像和成分列表。那就是SingleIngredient小部件正在做的事情。那么,如何才能一个一个地遍历每个列表?

 Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
          future: getIngredients(),
          builder: (context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (context, index) {
                  DocumentSnapshot user = snapshot.data.documents[index];

                  return SingleIngredient(
                    // Access the fields as defined in FireStore
                    ingredient_name: user.data['ingredients'][index].toString(),
                  );
                },
              );
            } else if (snapshot.connectionState == ConnectionState.done &&
                !snapshot.hasData) {
              // Handle no data
              return Center(
                child: Text("No users found."),
              );
            } else {
              // Still loading
              return CircularProgressIndicator();
            }
          }),
    );
  }
}

3 个答案:

答案 0 :(得分:0)

Dart不知道您从Future返回什么类型,因此它将其解释为动态对象,该对象上没有长度获取器。更改方法

Future getIngredients() async {
return Firestore.instance
    .collection('ingredients')
    .where("name", isEqualTo: widget.dish_name.toString().toLowerCase()).getDocuments();

}

收件人

Future<List<YourType>> getIngredients() async {
return Firestore.instance
    .collection('ingredients')
    .where("name", isEqualTo: widget.dish_name.toString().toLowerCase()).getDocuments();

}

其中,YourType是从getDocuments()函数返回的类型。您可能还需要对其执行toList()。

答案 1 :(得分:0)

这是一个使用StreamBuilder的示例,其中我从集合中检索所有文档并构建一个ListView来显示它们:

Widget buildUserList(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (snapshot.hasData) {
        return ListView.builder(
            itemCount: snapshot.data.documents.length,
            itemBuilder: (context, index) {
                DocumentSnapshot user = snapshot.data.documents[index];

                return ListTile(
                    // Access the fields as defined in FireStore
                    title: Text(user.data['firstName']),
                    subtitle: Text(user.data['lastName']),
                );
            },
        );
    } else if (snapshot.connectionState == ConnectionState.done && !snapshot.hasData {
        // Handle no data
        return Center(
            child: Text("No users found."),
        );
    } else {
        // Still loading
        return CircularProgressIndicator();
    }
}

用法:

Scaffold(
    body: StreamBuilder(
        stream:
            Firestore.instance.collection('users').snapshots(),
        builder: buildUserList,
    )
)

Scaffold(
    body: FutureBuilder(
        future:
            Firestore.instance.collection('users').getDocuments(),
        builder: buildUserList,
    )
)

答案 2 :(得分:0)

body: StreamBuilder(
stream: Firestore.instance
    .collection('ups')
.where('pc',
isEqualTo: widget.post.data["pc"])
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: Text("Loading..."),
);
} else {
final ups = snapshot.data.documents;
List<String> stateWidget = [];
for (var message in ups) {
final stateText = message.data['state'];
// final stateCollection = Text('$stateText');
stateWidget.add(stateText);
}enter code here
return  ListView(
children: stateWidget
    .map((data) => ListTile(`enter code here`
title: Text(data),
onTap: () => {_selectedItem(data)}))
    .toList(),`enter code here`
)