簡體   English   中英

如何在 flutter 中顯示來自 firestore 的類別列表?

[英]How to show category list from firestore in flutter?

我有一個名為 collection 的產品,在那個產品集合中我保存了產品及其名稱和類別。 現在我需要創建一個標簽欄,其中包含產品內的所有類別列表。 問題是同一類別有多個產品。 我希望該類別顯示一次。 如何做到這一點?

這是我的代碼:

StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
  stream: FirebaseFirestore.instance.collection('products') .where("category").snapshots(),
  builder: (_, snapshot) {
    if (snapshot.hasError) return Text('Error = ${snapshot.error}');

    if (snapshot.hasData) {

      final docs = snapshot.data!.docs;

      return ListView.builder(
        itemCount: docs.length,
        itemBuilder: (_, i) {
          
          final data = docs[i].data();
          Set s = {};
          s.add( data["category"]);
          
          return ListTile(
            title: Text(s.elementAt(0).toString()),
            
          );
        },
      );
    }

    return Center(child: CircularProgressIndicator());
  },
)

你必須提供你的代碼,

猜測這段代碼將幫助你實現你的代碼....

在這里我拍了電影而不是產品..你可以根據你的要求更正它......


class Movie {
  String name;
  String category;
  String language;
  int rating;

  Movie(
      {required this.name,
      required this.category,
      required this.language,
      required this.rating});
}

void main() {
  List<Movie> movielist = [
    Movie(name: 'Golmaal', category: 'Comedy', language: 'Hindi', rating: 5),
    Movie(name: 'Naseeb', category: 'Classic', language: 'Hindi', rating: 5),
    Movie(name: 'Hera Phery', category: 'Comedy', language: 'Hindi', rating: 5)
  ];

  final categories = movielist.map((e) => e.category).toSet();//this will generate unique category list..

  print(categories);
// now use this categories to ur design with listview or any list widgets
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM