Home > Back-end >  Couldnt Read Data From Firetore
Couldnt Read Data From Firetore

Time:06-29

I am trying to read data from Firebase Firestore, but I am not able to do so, and I have some Errors. I did it before this way and it worked but now I think the way to read data is changed.

The Error ( The property 'docs' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!'). )

adding a null check does not solve the problem. Firestore has no rules to block the data

lass Toyota extends StatefulWidget {
  const Toyota({Key? key}) : super(key: key);

  @override
  State<Toyota> createState() => _ToyotaState();
}

class _ToyotaState extends State<Toyota> {
  final firestore = FirebaseFirestore.instance.collection("toyota").get();

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      body: StreamBuilder(
          stream: FirebaseFirestore.instance.collection('singers').snapshots(),
          builder: (context, snapshot) {
            return ListView.builder(
              itemCount: (snapshot.data as QuerySnapshot).docs.length,
              itemBuilder: (context, index) =>  Text(
                           ////// Here is the problem ( The docs )
                            snapshot.data.docs[index]["price"],
                           
                          ),

CodePudding user response:

(snapshot.data! as QuerySnapshot).docs.length

write like this at itemcount instead of it

(snapshot.data as QuerySnapshot).docs.length,

if still any confusion then ask me

CodePudding user response:

You need to put a condition for when your snapshot has data

here is an example:

if (snapshot.hasData) {
          return ListView.builder(
              itemCount: snapshot.data.docs.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(snapshot.data.docs[index].data()['name']),
                  subtitle: Text(snapshot.data.docs[index].data()['age']),
                );
              });
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }

CodePudding user response:

static final FirebaseFirestore _firestore = FirebaseFirestore.instance;

QuerySnapshot snapshot = await _firestore
        .collection('toyota')
        .get();

Check this out.

  • Related