'The operator '[]' isn't defined for the type 'Object'. Flutter Dart
Hello, could you help me with this error, I don't know how to solve it
import 'package:firebase_database/firebase_database.dart';
class Users {
String id;
String email;
String name;
String phone;
Users({
this.id,
this.email,
this.name,
this.phone,
});
Users.fromSnapshot(DataSnapshot dataSnapshot) {
id = dataSnapshot.key;
email = dataSnapshot.value["email"];
name = dataSnapshot.value["name"];
phone = dataSnapshot.value["phone"];
}
}
Solution 1:[1]
Try this
Users.fromSnapShot(DataSnapshot dataSnapshot) {
var data = dataSnapshot.value as Map?;
id = dataSnapshot.key;
email = data?["email"];
name = data?["name"];
phone = data?["phone"];
print("Users email $email");
print("Users name $name");
print("Users phone $phone");
}
Solution 2:[2]
From the documentation, DataSnapshot.value
is a type Object?
. This type doesn't define an indexer like List
or Map
does, so you can't use an indexer on it.
However, since Object
is the superclass of everything, value
could be typed as Object
but actually be a Map
. You can try to cast it to a Map
first if you like, but you should only do this if you know that it is a Map
. If it's not, then casting it will result in a runtime error. (You can do print(dataSnapshot.value.runtimeType)
and see what it says before you make your decision.)
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 | Pannam |
Solution 2 | Abion47 |