Pamela
Pamela

Reputation: 475

Expected a value of type 'QuerySnapshot<Object?>', but got one of type '_MapStream<QuerySnapshotPlatform, QuerySnapshot<Map<String, dynamic>>>'

My goal is to get data from Firestore, then add the data to a list, the simplest way possible.

Please take note that I would like to do this without using Streambuilder because I'll be using the data list for another package which doesn't need a Streambuilder

This is the code:

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

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

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

class _HomeState extends State<Home> {

  bool isFirstTime = false;
  List<DocumentSnapshot> datas = [];

  getData() async {
    print("Getting data");
    if (!isFirstTime) {
      QuerySnapshot snap = (await FirebaseFirestore.instance
          .collection('poll')
          .snapshots()) as QuerySnapshot<Object?>;
      isFirstTime = true;
      setState(() {
        datas.addAll(snap.docs);
      });
    }
  }

  @override
  void initState() {
    print("Hello");
    getData();
    print(datas);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.pink[200],
        body: Padding(
          padding: const EdgeInsets.all(15),
          child: Column(
            children: const [
              Text(
                "Hello, world",
                style: TextStyle(color: Colors.black),
              ),
              Text(
                "Hello, world",
                style: TextStyle(color: Colors.black),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Item {
  Item({this.option, this.optionVotes});
  final String? option;
  final int? optionVotes;
}

When I print the list, it's empty. Also, I receive this error:

enter image description here

Console screenshot for extra reference:

enter image description here

Upvotes: 0

Views: 245

Answers (1)

griffins
griffins

Reputation: 8246

.snapshot() returns Stream<QuerySnapshot<Map<String, dynamic>>> so how do you get your data without a stream, you should use .get() which returns QuerySnapshot<Map<String, dynamic>>> example

final querySnapshot = await await FirebaseFirestore.instance
          .collection('poll')
//always good to limit
            .limit(7)
            .get();

Upvotes: 1

Related Questions