type '_JsonQuerySnapshot' is not a subtype of type 'Map<String, dynamic>' in type cast"

Viewed 4789

I have issues to display data from Firebase. Here is the code I used in my FutureBuilder.

This is the error that I got

"The following _CastError was thrown building FutureBuilder<QuerySnapshot<Object?>>(dirty, state: _FutureBuilderState<QuerySnapshot<Object?>>#c8a1c):
type '_JsonQuerySnapshot' is not a subtype of type 'Map<String, dynamic>' in type cast"

Code

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:errandkaba_app/widgets/custom_action_bar.dart';
import 'package:flutter/material.dart';

class ServicePage extends StatefulWidget {
  final String? serviceId;
  const ServicePage({Key? key, this.serviceId}) : super(key: key);

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

class _ServicePageState extends State<ServicePage> {
  final CollectionReference _servicesRef =
  FirebaseFirestore.instance.collection("cleaning");



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          FutureBuilder (
            future: _servicesRef.get(),
            builder: (context, snapshot){
              //if has error
              if (snapshot.hasError) {
                return Scaffold(
                  body: Center(
                    child: Text("Error ${snapshot.error}"),
                  ),
                );
              }

              if(snapshot.connectionState == ConnectionState.done){
                Map<String, dynamic> documentData = snapshot.data as Map<String, dynamic>;

                return ListView(
                  children: [
                    Image.network(
                        "${documentData['images'][0]}"
                    ),
                  ],
                );

              }
5 Answers

try snapshot.data to snapshot.data!.data()

I did this FutureBuilder<DocumentSnapshot<Object?>>(future: _servicesRef.doc(widget.serviceId).get() and used this Map<String, dynamic> documentData = snapshot.data!.data() as Map<String, dynamic>; and it worked.

Change the FutureBuilder to FutureBuilder<QuerySnapshot> (or StreamBuilder< QuerySnapshot> for StreamBuilder)

Then cast the data this way

List<Map<String, dynamic>> documentData = snapshot.data?.docs.map((e) => e.data() as Map<String, dynamic>?).toList();
FutureBuilder(
  future: FirebaseFirestore.instance.collection('users').doc(userId).get(),
  builder: (ctx,*AsyncSnapshot<DocumentSnapshot<Map<String,dynamic>>>* snapshot){
    return Text(
      snapshot.connectionState == ConnectionState.waiting
        ? 'Loading...'
        : snapshot.data!.data()!['userName'],
      .....

Provide the type and then it will work as expected else you will have to cast it to the right type before using data.data() prop and fun..

make your FurtureBuilder like this FurtureBuilder then snapshot.data.data()

Related