'snapshot.value giving me error "The operator '[]' isn't defined for the type 'Object'. "

****initially the app was giving me error "" The method '[]' can't be unconditionally invoked because the receiver can be 'null'" then i apply null safety and the error changed to "The operator '[]' isn't defined for the type 'Object'. if I print snapshot.value the data get prints in console but when i put snapshot.value in text or image fields it gives me these two error i am stuck on this from 2 days ****

import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';
import 'package:firebase_storage/firebase_storage.dart';

import 'PostScreen.dart';
class HomeScreen extends StatefulWidget {
 const HomeScreen({Key? key}) : super(key: key);

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

class _HomeScreenState extends State<HomeScreen> {
 final dbRef=FirebaseDatabase.instance.reference().child('Post');
 
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       automaticallyImplyLeading: false,
       backgroundColor: Colors.deepOrange,
       title: Text("new blog"),
       centerTitle: true,
       actions: [
         InkWell(
           onTap: (){
           Navigator.push(context, MaterialPageRoute(builder: (context)=> PostScreen()));
           },

        child: Icon(Icons.add)),
         SizedBox(width: 20,)
       ],
     ),
     body:
       FirebaseAnimatedList(
         query: dbRef.child("Post List"),
         itemBuilder: (BuildContext context,DataSnapshot snapshot,Animation<double> animation, int x){
           var ss=snapshot.value;
           print(ss);


         return
             Padding(
               padding: const EdgeInsets.symmetric(horizontal:15,vertical: 20),
               child: Card(
               elevation: 4.0,
               child: Column(
                 children: [
                   ListTile(
                     title: Text(snapshot.value!['pTitle']),
                     // subtitle: Text('subheading'),
                     trailing: Icon(Icons.favorite_outline),
                   ),
                   Container(
                     height: 200.0,
                     child: Ink.image(
                       image: AssetImage(snapshot.value['pImage']),
                       fit: BoxFit.cover,
                     ),
                   ),
                   Container(
                     padding: EdgeInsets.all(16.0),
                     alignment: Alignment.centerLeft,
                     child: Text(snapshot.value!['pDescription']),
                   ),
                   ButtonBar(
                     children: [
                       TextButton(
                         child: const Text('CONTACT AGENT'),
                         onPressed: () {/* ... */},
                       ),
                       TextButton(
                         child: const Text('LEARN MORE'),
                         onPressed: () {/* ... */},
                       )
                     ],
                   )
                 ],
               )),
             );

         }
       ),
     );

 }
}




Solution 1:[1]

You have to convert snapshot.value to Map because it is of type Object

Simply use:

Map map = Map.from(snapshot.value as Map);

For your code, try this:

import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';
import 'PostScreen.dart';


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

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

class _HomeScreenState extends State<HomeScreen> {
  final dbRef = FirebaseDatabase.instance.reference().child('Post');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: Colors.deepOrange,
        title: const Text("new blog"),
        centerTitle: true,
        actions: [
          InkWell(
            onTap: () {
               Navigator.push(context, MaterialPageRoute(builder: (context)=> PostScreen()));
            },
            child: const Icon(Icons.add),
          ),
          const SizedBox(width: 20)
        ],
      ),
      body: FirebaseAnimatedList(
        query: dbRef.child("Post List"),
        itemBuilder: (BuildContext context, DataSnapshot snapshot,
            Animation<double> animation, int x) {
          Map m = Map.from((snapshot.value ?? {}) as Map);

          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 20),
            child: Card(
              elevation: 4.0,
              child: Column(
                children: [
                  ListTile(
                    title: Text(m['pTitle']),
                    // subtitle: Text('subheading'),
                    trailing: const Icon(Icons.favorite_outline),
                  ),
                  SizedBox(
                    height: 200.0,
                    child: Ink.image(
                      image: AssetImage(m['pImage']),
                      fit: BoxFit.cover,
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.all(16.0),
                    alignment: Alignment.centerLeft,
                    child: Text(m['pDescription']),
                  ),
                  ButtonBar(
                    children: [
                      TextButton(
                        child: const Text('CONTACT AGENT'),
                        onPressed: () {/* ... */},
                      ),
                      TextButton(
                        child: const Text('LEARN MORE'),
                        onPressed: () {/* ... */},
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

Solution 2:[2]

Do this title: Text((snapshot.value as dynamic)['pTitle']), or you can initialize like this dynamic ss = snapshot.value;

title: Text(ss['pTitle']),

Saw answer here and it worked for me "The operator '[]' isn't defined" error when using .data[] in flutter firestore

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Josteve
Solution 2 Michael Akouwa