简体   繁体   中英

how to get value from map in firebase database flutter

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.

---------- Update ----------

Hi Frank, firstly thanks for your reply, I will get a stream from firebase RTDB, since the data structure is as displayed above, with the data I got from following method,

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

the key from this data will be {"-My6relBpWvPaY_I4JvN"} , and value is

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

so in this case I need to update the method you showed

//**instead** snapshot.children.forEach((msgSnapshot) {
  data.values.forEach((msgSnapshot) {

  final Map<String, dynamic> messageData = Map<String, dynamic>.from(msgSnapshot as Map);
  //i am not sure whether I need to use msgSnapshot.value as Map, since msgSnaphot is already the right Map<String, dynamic> that I can put to fromJson      

  Message message = Message.fromJson(messageData);

})

Do I understand correctly? thanks for further info!!

I have it setup like this in my case witch works just fine:

  static Message model({required Map map}) => Message(
        messageID: map[kModelMessengerID],
        owner: map[kModelMessageOwner],
        type: map[kModelMessageType],
        msg: map[kModelMessageMsg],
        membersIDs: (map[kModelMessageMembersIDs] as List<dynamic>)
            .map((e) => e.toString())
            .toList(),
        createdAt: map[kModelMessageCreatedAt] == null
            ? DateTime.now()
            : (map[kModelMessageCreatedAt] as Timestamp).toDate(),
      );

and with how I pass data in to it:

final ref = FirebaseDatabase.instance.ref();
final snapshot = await ref.child(...).get();

if (snapshot.exists) {
    var m  = Message.model(map: snapshot.value as Map))
} else {
    print('No data available.');
}

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}');
})

Your JSON should look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM