[英]how to where query a collectionGroup in firestore flutter?
[英]How do I filter CollectionGroup Query with 'where' in Flutter Firestore
我有一個 CollectionGroup 查詢,它使用 Streambuilder 和 ListView 在 Listtile 中顯示來自“school_news”集合的所有文檔數據。
但現在我只想在 ListView/Listtile 中顯示文檔數據,其中“名稱”字段等於列表中的名稱,例如:
List userSelections = ['Liebenberg', 'St Michaels' , 'School C' ];
FirebaseFirestore.instance
.collectionGroup('school_news')
.where('name', arrayContainsAny: userSelections )
.snapshots(),
所以我現在想要的是僅在 ListView/Listtile 中顯示文檔數據字段,其中“名稱”字段是 Liebenberg、St Michaels 和“School C”,而不是“school_news”集合中的所有文檔數據。
這樣的事情可能嗎? 我試過上面的代碼但沒有運氣,所以我不確定我錯過了什么。
任何幫助或指導將不勝感激。謝謝
更新
我已根據答案更新並包含完整代碼,如下所示:
class UserHome extends StatefulWidget {
const UserHome({Key? key}) : super(key: key);
@override
_UserHomeState createState() => _UserHomeState();
}
class _UserHomeState extends State<UserHome> {
final uid = FirebaseAuth.instance.currentUser!.uid;
final db = FirebaseFirestore.instance;
List userSelections = ['Liebenberg', 'St Michaels'];
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collectionGroup('school_news')
.where('name', whereIn: userSelections)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: Text('Loading '),
);
} else
return ListView(
children: snapshot.data!.docs.map((doc) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {},
child: Column(
children: [
ListTile(
leading: Text(doc['title']),
),
SizedBox(
height: 10,
),
],
),
),
);
}).toList(),
);
},
),
);
}
}
似乎沒有返回任何數據,因為頁面只顯示“正在加載”。 我也沒有得到為“WhereIn”創建新索引的鏈接。
我做錯了什么嗎?
感謝你目前的幫助。
您應該使用whereIn
而不是arrayContainsAny
。 替換這一行
.where('name', arrayContainsAny: userSelections )
有了這個:
.where('name', whereIn: userSelections)
請記住,Firestore 有一個內置限制,您的列表中的項目不能超過 10 個。 這意味着你的列表userSelections
不能有超過 10 個值(否則你可能想做過濾器客戶端,這取決於你的用例)
此外,在您的第一次執行中,您可能需要添加一個新索引...只需點擊 web 鏈接(在新的錯誤消息中),這將有助於直接在 Firestore 中創建此必需的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.