[英]Flutter Dynamic TabBar for data coming from FireStore Collection
I have a FireStore collection named "products" and in there I have documents consisting of product data such as name, price, and category.我有一个名为“products”的 FireStore 集合,其中包含包含名称、价格和类别等产品数据的文档。 It follows the structure like this
它遵循这样的结构
{"name": "Milk Shake Strawberry",
"price": "250",
"category": "Drinks"
},
{"name": "Swiss Roll",
"price": "150",
"category": "Cake"
}
. .
I want to create the UI to show Each category as a Tab (ex: Drinks Tab, Cake Tab) and inside that tab, I want to show products related to that exact category.我想创建 UI 以将每个类别显示为选项卡(例如:饮料选项卡、蛋糕选项卡),并在该选项卡内显示与该确切类别相关的产品。
How can I achieve this in Flutter?我怎样才能在 Flutter 中实现这一点?
Try this尝试这个
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.