I want to get data from firebase and an error has occurred.
this is the code :
late final dref = FirebaseDatabase.instance.reference();
late DatabaseReference databaseReference;
showData(){
dref.once().then((snapshot){
print(snapshot.snapshot.value);
});
}
@override
void initState(){
super.initState();
databaseReference = dref;
}
child:
Container(
height:300,
child: GridView.count(
crossAxisCount: 2,
crossAxisSpacing: 12,
mainAxisSpacing: 8,
childAspectRatio: 1.30,
children: [
FirebaseAnimatedList(
shrinkWrap:true,
query: databaseReference,
itemBuilder: ( BuildContext context, DataSnapshot snapshot, Animation animation, int index){
return ListTile(
title: Text(snapshot.value!["intime"]),
subtitle : _parkingslot(name:'Floor'),);
}),
it has an error. That '[' got a red underline and the sentence is : Returns the contents of this data snapshot as native types. The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').
I've tried to add '!' and '?.' but still got an error, but the sentence is : The operator '[]' isn't defined for the type 'Object'.
please help
CodePudding user response:
There is no guarantee that snapshot.value
is a Map
, since it is declared as returning an Object?
. If you know for certain that it returns a map, you'll have to tell the compiler about that by casting the result:
itemBuilder: ( BuildContext context, DataSnapshot snapshot, Animation animation, int index){
var map = Map<String, dynamic>.from(snapshot.value! as Map; //