41 lines
1.5 KiB
Dart
41 lines
1.5 KiB
Dart
class MessageModel {
|
||
final int? id; // ID из базы данных (null, если сообщение еще не отправлено)
|
||
final int senderId; // ID отправителя
|
||
final int receiverId; // ID отправителя
|
||
final String text; // Текст сообщения
|
||
final DateTime createdAt; // Время отправки
|
||
final bool isMe; // Локальный флаг для UI (мое/чужое)
|
||
|
||
MessageModel({
|
||
this.id,
|
||
required this.senderId,
|
||
required this.receiverId,
|
||
required this.text,
|
||
required this.createdAt,
|
||
this.isMe = false,
|
||
});
|
||
|
||
// Превращаем JSON от бэкенда в объект Dart
|
||
factory MessageModel.fromJson(Map<String, dynamic> json, int currentUserId) {
|
||
return MessageModel(
|
||
id: json['id'],
|
||
senderId: json['sender_id'],
|
||
receiverId: json['receiverId'],
|
||
text: json['text'] ?? '',
|
||
// Парсим дату из ISO строки или временной метки
|
||
createdAt: DateTime.parse(json['created_at']),
|
||
// Сразу вычисляем, наше ли это сообщение
|
||
isMe: json['sender_id'] == currentUserId,
|
||
);
|
||
}
|
||
|
||
// Превращаем объект Dart в JSON для отправки через WebSocket или API
|
||
Map<String, dynamic> toJson() {
|
||
return {
|
||
'text': text,
|
||
'sender_id': senderId,
|
||
// На бэкенд обычно отправляем строку в формате ISO 8601
|
||
'created_at': createdAt.toIso8601String(),
|
||
};
|
||
}
|
||
} |