Home > OS >  The getter 'docs' isn't defined for the type 'DocumentSnapshot<Map<String,
The getter 'docs' isn't defined for the type 'DocumentSnapshot<Map<String,

Time:06-14

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

class ListStudentPage extends StatefulWidget {
  State<StatefulWidget> createState() {
    return _ListStudentPage();
  }
}

class _ListStudentPage extends State<ListStudentPage> {
  final Stream<DocumentSnapshot<Map<String, dynamic>>> productsStream =
      FirebaseFirestore.instance
          .collection('Categories')
          .doc('Pharmacy')
          .snapshots();

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
        stream: productsStream,
        builder: (BuildContext context,
            AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> snapshot) {
          if (snapshot.hasError) {
            print('Something went Wrong');
          }
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          }
          final List productDocs = [];
          snapshot.data!.docs.map((DocumentSnapshot document) {
            Map a = document.data() as Map<String, dynamic>;
            productDocs.add(a);
            a['id'] = document.id;
          }).toList();
        });
  }
}

I am getting this error "The getter 'docs' isn't defined for the type 'DocumentSnapshot<Map<String, dynamic>>" in the line right below( snapshot.data!.docs.map((DocumentSnapshot document,docs here is highlighted with a red underline) ) , where I created an empty list , can anyone please tell me why I am getting this error and how can I fix it .

CodePudding user response:

Use QuerySnapshot<Map<String, dynamic>> , because its used when your getting a stream or a list which is the case for you now, while use DocumentSnapshot<Map<String, dynamic>> when your getting a single item.

CodePudding user response:

Your productsStream refers to a single document named Pharmacy under the Category collection. Since you're reading only a single document, there is no need for the snapshot.data!.docs.map and you can just return a single widget for the one document you loaded.

Something like this for example:

return StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
    stream: productsStream,
    builder: (BuildContext context,
        AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> snapshot) {
      if (snapshot.hasError) {
        print('Something went Wrong');
      }
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Center(child: CircularProgressIndicator());
      }
      return Text(snapshot.data!.get('id')); //            
  • Related