![](/img/trans.png)
[英]How to iterate and sum value of data coming from firestore with flutter
[英]Flutter Dynamic TabBar for data coming from FireStore Collection
我有一個名為“products”的 FireStore 集合,其中包含包含名稱、價格和類別等產品數據的文檔。 它遵循這樣的結構
{"name": "Milk Shake Strawberry",
"price": "250",
"category": "Drinks"
},
{"name": "Swiss Roll",
"price": "150",
"category": "Cake"
}
.
我想創建 UI 以將每個類別顯示為選項卡(例如:飲料選項卡、蛋糕選項卡),並在該選項卡內顯示與該確切類別相關的產品。
我怎樣才能在 Flutter 中實現這一點?
嘗試這個
class ProductCategoryTabs extends StatefulWidget {
@override
_ProductCategoryTabsState createState() => _ProductCategoryTabsState();
}
class _ProductCategoryTabsState extends State<ProductCategoryTabs> {
List<String> _tabs = [];
Map<String, List<Product>> _products = {};
@override
void initState() {
super.initState();
// Fetch the list of categories and products from Firestore
Firestore.instance.collection('products').getDocuments().then((snapshot) {
snapshot.documents.forEach((document) {
var product = Product.fromFirestore(document);
if (!_tabs.contains(product.category)) {
_tabs.add(product.category);
}
if (_products[product.category] == null) {
_products[product.category] = [product];
} else {
_products[product.category].add(product);
}
});
setState(() {});
});
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: _tabs.length,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: _tabs.map((String tab) {
return Tab(text: tab);
}).toList(),
),
),
body: TabBarView(
children: _tabs.map((String tab) {
return ListView.builder(
itemCount: _products[tab].length,
itemBuilder: (BuildContext context, int index) {
return ProductTile(product: _products[tab][index]);
},
);
}).toList(),
),
),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.