Reputation: 1
I tried to do a simple firestore query in flutter, however it always returns an empty snapshot. With the collection categories it already worked. The code for the products was actually only copy pasted.
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:foodandfast/services/models.dart';
class FirestoreService {
final FirebaseFirestore _db = FirebaseFirestore.instance;
Future<List<Category>> getCategories() async {
var ref = _db.collection("categories");
var snapshot = await ref.orderBy("name", descending: false).get();
var data = snapshot.docs.map((s) {
var element = s.data();
element\["id"\] = s.id;
element\["imageName"\] += ".png";
return element;
});
var categories = data.map((d) => Category.fromJson(d));
return categories.toList();
}
Future<List<Product>> getProducts(String categoryId) async {
var ref = FirebaseFirestore.instance.collection("products");
var snapshot = await ref
.orderBy("name", descending: false)
.where('categoryId', isEqualTo: categoryId)
.get();
print(snapshot.docs.length);
var data = snapshot.docs.map((s) {
var element = s.data();
element\["id"\] = s.id;
element\["imageName"\] += ".png";
return element;
});
var products = data.map((d) => Product.fromJson(d));
return products.toList();
}
}]
Upvotes: 0
Views: 587
Reputation: 60
There is no categoryId field in Products collections, thats why getProducts()
returns empty.
however, firebase is noSQL database, unlike SQL you can't apply the principle of foreign key in noSQL.
you need to learn more about data modeling in noSQL database.
Upvotes: 1