Reputation: 57
I'm getting an error when trying to retrieve data from a subcollection. The firestore db is as follows -> users; doc uid; messages; loans approved; loans approved.
I have double checked that I typed the doc and collections correctly so what am I missing?
Any suggestions would be appreciated.
Thank you
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class MessagesScreen extends StatefulWidget {
@override
MessagesScreenState createState() => MessagesScreenState();
}
FirebaseAuth _auth = FirebaseAuth.instance;
final uid = _auth.currentUser!.uid;
var boldFont = TextStyle(fontFamily: 'Inter', fontWeight: FontWeight.w600);
class MessagesScreenState extends State<MessagesScreen> {
final db = FirebaseFirestore.instance
.collection('users')
.doc(uid)
.collection('Messages')
.snapshots();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
titleSpacing: 30,
automaticallyImplyLeading: false,
backgroundColor: Color.fromRGBO(1, 67, 55, 1),
toolbarHeight: 100,
title: new Text(
'Messages',
style: TextStyle(
color: Color.fromRGBO(255, 255, 255, 1),
fontFamily: 'Poppins',
fontSize: 25,
letterSpacing: 1.2,
fontWeight: FontWeight.bold,
height: 1),
),
),
body: StreamBuilder<QuerySnapshot>(
stream: db,
builder: (context, snapshot) {
if (!snapshot.hasData)
return const Center(
child: CircularProgressIndicator(),
);
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (BuildContext context, int index) {
return snapshot.data!.docs[index]['Loans approved']
['Loans overdue']['Loans paid'];
});
},
));
}
}
Upvotes: 1
Views: 245
Reputation: 83093
The reason is that you define the Stream (your db
variable) as
FirebaseFirestore.instance
.collection('users')
.doc(uid)
.collection('Messages')
.snapshots();
Based on your screenshot, there is one Loans approved
document in this Messages
collection which does not have any data. This document has a Loans approved
subcollection which, in turns, contains a Loans approved
document. It is this doc that contains the fields (Interest
, Loan amount
, etc.).
So defining your Stream as follow should do the trick:
FirebaseFirestore.instance
.collection('users')
.doc(uid)
.collection('Messages')
.doc('Loans approved')
.collection('Loans approved')
.snapshots();
PS: I would advise you to use the camelCase convention when writing collections, docs and field names.
Upvotes: 1