繁体   English   中英

Flutter 来自 FireStore 集合的数据的动态 TabBar

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM