Home > Blockchain >  how to get value from map in firebase database flutter
how to get value from map in firebase database flutter

Time:03-14

i have a json structure like this

{
  "-My6relBpWvPaY_I4JvN": {
    "idUser": "4dca8440-a37d-11ec-9c66-9b8f61be17f0", 
    "message": "777777"
  }
}

and I wanna use fromJson to save to map, here is my model:

class Message {
  final String userId;
  final String message;

  const Message({
    @required this.userId,
    @required this.message,
  });

  static Message fromJson(Map<String, dynamic> json) => Message(
        userId: json['idUser'],
        message: json['message'],
      );


  Map<String, dynamic> toJson() => {
        'idUser': userId,
        'message': message,
      };
}

right now I always get null from the help from Frank,

final data = Map<String, dynamic>.from(snapshot.value as Map);
Message message = Message.fromJson(data);

print('message value${message.message}'); // here i got null

please tell me where is wrong.

CodePudding user response:

The code in your question doesn't show how snapshot is initialized, but my guess is that it contains a list of messages. Even a list of 1 messages is still a list, so you have to handle that in your code by iterating of the children property of the snapshot:

snapshot.children.forEach((msgSnapshot) {
  final data = Map<String, dynamic>.from(msgSnapshot.value as Map);
  Message message = Message.fromJson(data);

  print('message value${message.message}');
})

CodePudding user response:

Your JSON should look like this:

{"userId": "4dca8440-a37d-11ec-9c66-9b8f61be17f0", "message": "777777"}

  • Related