-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatmessage_model.dart
More file actions
46 lines (38 loc) · 1.16 KB
/
chatmessage_model.dart
File metadata and controls
46 lines (38 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import 'dart:convert';
class ChatMessageModel {
final String text;
final bool isUser;
final DateTime timestamp;
ChatMessageModel({
required this.text,
required this.isUser,
DateTime? timestamp,
}) : timestamp = timestamp ?? DateTime.now();
factory ChatMessageModel.fromJson(Map<String, dynamic> json) {
final parsedTimestamp =
DateTime.tryParse(json['timestamp']?.toString() ?? '') ?? DateTime.now();
return ChatMessageModel(
text: json['text']?.toString() ?? '',
isUser: json['isUser'] as bool? ?? true,
timestamp: parsedTimestamp,
);
}
Map<String, dynamic> toJson() {
return {
'text': text,
'isUser': isUser,
'timestamp': timestamp.toIso8601String(),
};
}
static String encodeList(List<ChatMessageModel> messages) {
return jsonEncode(messages.map((message) => message.toJson()).toList());
}
static List<ChatMessageModel> decodeList(String raw) {
final decoded = jsonDecode(raw);
if (decoded is! List) return [];
return decoded
.whereType<Map>()
.map((item) => ChatMessageModel.fromJson(Map<String, dynamic>.from(item)))
.toList();
}
}