0

Picture of my error

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"];
  }
}
2
  • Are you sure "value" is what you're looking for? The auto complete will tell you which type is it. DataSnapshot is not a map... don't expect to use it as such. Is a complex object with many variables. Commented Jan 3, 2022 at 16:58
  • You need to share your database model as well. Commented Jan 3, 2022 at 17:51

2 Answers 2

2

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");
  }
Sign up to request clarification or add additional context in comments.

Comments

0

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.