I finished setting up my app's functionality to save text-based messages to RTDB (see code below). I now need to be able to save a voice recording that the user records into RTDB. These voice recordings will be interweaved with text-based messages (it's a group chat app), i.e. users can either send a regular text message or send a voice recording. How do I modify my message model the code to save a record to RTDB to accomplish this? Is it even possible to save an audio file into RTDB?
message.dart
class Message { //text messages only
final String uid;
final String text;
final DateTime timestamp;
final String type;
Message({
required this.uid,
required this.text,
required this.timestamp,
required this.type,
});
Message.fromJson(Map<dynamic, dynamic>? json): //Transform JSON into Message
uid = json?['uid'] as String,
text = json?['text'] as String,
timestamp = DateTime.parse(json?['timestamp'] as String),
type = json?['type'] as String;
Map<dynamic, dynamic> toJson() => <dynamic, dynamic>{ //Transforms Message into JSON
'uid': uid,
'text': text,
'timestamp': timestamp.toString(),
'type': type,
};
}
message_dao.dart
class MessageDao {
MessageDao({required this.groupIDPath}): _messagesRef = FirebaseDatabase.instance.reference().child(groupIDPath);
String groupIDPath;
DatabaseReference _messagesRef;
//Save a single message to the appropriate node based on groupIDPath
void saveMessage(Message message) {
_messagesRef.push().set(message.toJson());
}
rest of code...
}
CodePudding user response:
The Firebase Realtime Database can only store JSON types. Storing audio files in the Realtime Database is going to be highly inefficient, as you'd need to convert them to a JSON type (typically base64).
I recommend instead storing the files itself in Cloud Storage, for which there's also a Firebase SDK, and then store a reference to that file (for example its download URL) in the Realtime Database.
To learn more about this, see the documentation on uploading files and getting the download URL.