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
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.What is a type data that you’re try to show from Firebase ?
can you screenshot the data you get from firebase ?