skip to Main Content

I have written the below code to fetch real-time database data into a listview. The problem is that when the app is run on an Android device, I see a red screen with the error "type ‘List<Object?>’ is not a subtype of type ‘Map<dynamic, dynamic’ in type cast.enter code here

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final ref = FirebaseDatabase.instance.ref("Users").child("data");
  @override
  Widget build(BuildContext context) {
    return Scaffold(
     body: Column(
       children: [

         Expanded(
           child: StreamBuilder(
             stream: ref.onValue,
             builder: (context, AsyncSnapshot<DatabaseEvent> snapshot) {
               if (snapshot.hasError) {
                 return Text('Error: ${snapshot.error}');
               }

               if (!snapshot.hasData) {
                 return CircularProgressIndicator();
               } else {
                 Map<dynamic, dynamic> map = snapshot.data?.snapshot.value as Map<dynamic, dynamic>;
                 List<dynamic> list = [];
                 list.clear();
                 if (map != null) {
                   list = map.values.toList();
                 }
                 return ListView.builder(
                   itemCount: snapshot.data!.snapshot.children.length,
                   itemBuilder: (context, index) {
                     return ListTile(
                       title: Text(list[index]["id"]),
                       leading: Image.network(list[index]["image"]),
                     );
                   },
                 );
               }
             },
           ),
         ),
       ],
     ),
    );
  }
}

2

Answers


  1. You are trying to
    snapshot.data?.snapshot.value as Map<dynamic, String>;, to cast a List of dynamic values to a Map<dynamic,String>.

    Try by removing .value. And if that not helps, update with the new Error, I will update my Answer as well.

    Login or Signup to reply.
  2. What is a type data that you’re try to show from Firebase ?

    can you screenshot the data you get from firebase ?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search