Home > Net >  How to display all the names in database firestorefirebase flutter
How to display all the names in database firestorefirebase flutter

Time:04-11

In my app I have a model which consists of the store name and store image and looks like this:

class StoreModel
{
  String? imageofStore;
  String? storeName;

  StoreModel({ this.imageofStore, this.storeName});

  //data from server
  factory StoreModel.fromMap(map)
  {
    return StoreModel(
      imageofStore: map['imageofStore'],
      storeName: map['storeName'],
    );
  }

//  data to server
  Map<String, dynamic> toMap(){
    return{
      'imageofStore': imageofStore,
      'storeName': storeName,
    };
  }
}

and my database for stores looks like this: enter image description here

to call the store name I use initstate and setState as such:

 class addStore extends StatefulWidget {
  const addStore({Key? key}) : super(key: key);

  @override
  _addStoreState createState() => _addStoreState();
}

class _addStoreState extends State<addStore> {
  
  User ? user = FirebaseAuth.instance.currentUser;
  StoreModel storebox = StoreModel();
  
  @override
  void initState()
  {
    super.initState();
    FirebaseFirestore.instance
        .collection("stores")
        .doc("XQjbm665g2a2xAiiydjr")
        .get()
        .then((value){
      this.storebox = StoreModel.fromMap(value.data());
      setState(() {

      });
    });

  }
  
  @override
  Widget build(BuildContext context) {
    return Container(
     child: Text("${storebox.storeName}"),
    );
  }
}

With this, I get the store name of the store with id XQjbm665g2a2xAiiydjr displaying but the thing is I want to get the name of all the stores. I know I need to change the .doc() but im not sure as to what I am to put in it that will start displaying all the names. Can someone please help?

CodePudding user response:

By providing a document id, what you're getting is a DocumentSnapshot which is the data of a particular Document, but when you remove it, you get QuerySnapshot which is a list of the data of all the documents. So, to read all, you change your code as:

List<StoreModel> storesList = [];

FirebaseFirestore.instance
    .collection("stores")
    .get()
    .then((value){
  //Now, this value is of type QuerySnapshot unlike earlier.
  if (value != null && value.docs.isNotEmpty) {
  //If it comes here means the collection is not empty.

  //Because this value is a list of DocumentSnapshot, We've to map it to extract documents.
  //After mapping, returning it as a list and assigning it to storesList
  storesList = value.docs.map((doc) => StoreModel.fromMap(doc.data())).toList();
  setState(() {

  });
  } else {
  //If it comes here means there are no documents in your collection.
  //Notify User there's no data.
  }
});

This code will get all the documents your collection have, but, you can limit or filter using limit or where respectively, just place .limit(int) or .where() before .get().

CodePudding user response:

for model try to convert to json or you can use your either way this is just for example model

import 'dart:convert';

List<StoreModel> storeModelFromJson(String str) => List<StoreModel>.from(json.decode(str).map((x) => StoreModel.fromJson(x)));

String storeModelToJson(List<StoreModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class StoreModel {
    StoreModel({
        this.imageofStore,
        this.storeName,
    });

    final String? imageofStore;
    final String? storeName;

    factory StoreModel.fromJson(Map<String, dynamic> json) => StoreModel(
        imageofStore: json["imageofStore"] == null ? null : json["imageofStore"]!,
        storeName: json["storeName"] == null ? null : json["storeName"]!,
    );

    Map<String, dynamic> toJson() => {
        "imageofStore": imageofStore == null ? null : imageofStore!,
        "storeName": storeName == null ? null : storeName!,
    };
}

try this get all list

static Future<List<StoreModel>> getStorelist() async {
  List<dynamic> list = [];
  await FirebaseFirestore.instance
            .collection("stores")
            .get()
            .then((value){
          for(var x in value.docs){
            final Map<String,dynamic> toMap = x.data() as Map<String,dynamic>;
          /// Try to print all data first to see if fetching use log to view on terminal
          log(toMap.toString());

       
            list.add(toMap); 
        }
    });
   
    return list.map((e)= > StoreModel.fromJson(e)).toList();  
}

as in my case to get only 1 data

static getSingleName(String? uid) async {
    final result =
        await FirebaseFirestore.instance
            .collection("stores").doc(uid).get();
    final response = result.data() as Map<String, dynamic>;
    return response['storeName'].toString();
  }
  • Related