Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]' for Flutter

I am trying to store my database value into a class, but i was unable to convert it into my class using DataSnapshot. I have already added all necessary null safety operators. But it still shows an error.

class User {
  String userID = "";
  String name = "";
  String phoneNo = "";
  String email = "";
  String password = "";

  User(
      {required this.userID,
      required this.name,
      required this.phoneNo,
      required this.email,
      required this.password});

  User.fromSnapshot(DataSnapshot dataSnapshot) {
    userID = dataSnapshot.key!;
    if (dataSnapshot.value != null) {
      name = dataSnapshot.value!["name"] as String;
      email = dataSnapshot.value!['email'];
      phoneNo = dataSnapshot.value!['phone'];
      password = dataSnapshot.value!['password'];
    }
  }
}

I am trying to define the snapshot value as a String but also the same as others.

Error message

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

try

if (dataSnapshot.value != null) {
      final data = dataSnapshot.value as Map;
      name = data["name"] as String;
      email = data['email'] as String;
      phoneNo = data['phone'] as String;
      password = data['password'] as String;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading