post.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import 'attachment.dart';
  2. class Post {
  3. final String added;
  4. final List<Attachment> attachments;
  5. final Attachment? files;
  6. final String content;
  7. final String edited;
  8. final String id;
  9. final String published;
  10. final String service;
  11. final String title;
  12. final String user;
  13. final String baseUrl;
  14. Post({
  15. required this.added,
  16. required this.attachments,
  17. required this.files,
  18. required this.content,
  19. required this.edited,
  20. required this.id,
  21. required this.published,
  22. required this.service,
  23. required this.title,
  24. required this.user,
  25. required this.baseUrl,
  26. });
  27. List<Attachment> get mediaAttachments => files == null ? [
  28. ...attachments.where((a) => a.isImage || a.isVideo)
  29. ] : [
  30. ...attachments.where((a) => a.isImage || a.isVideo),files!
  31. ];
  32. factory Post.fromJson(Map<String, dynamic> json, String baseUrl) => Post(
  33. added: _parseString(json['added']),
  34. attachments: _parseAttachments(json['attachments'], baseUrl),
  35. files: (json["file"] as Map)?.isNotEmpty == true ? Attachment.fromJson(json["file"], baseUrl) : null,
  36. content: _parseString(json['substring']),
  37. edited: _parseString(json['edited']),
  38. id: _parseString(json['id']),
  39. published: _parseString(json['published']),
  40. service: _parseString(json['service']),
  41. title: _parseString(json['title']),
  42. user: _parseString(json['user']),
  43. baseUrl: baseUrl,
  44. );
  45. static String _parseString(dynamic value) =>
  46. (value is String) ? value : '';
  47. static List<Attachment> _parseAttachments(
  48. dynamic jsonData,
  49. String baseUrl
  50. ) {
  51. if (jsonData is! List) return [];
  52. return jsonData
  53. .whereType<Map<String, dynamic>>()
  54. .map((x) => Attachment.fromJson(x, baseUrl))
  55. .whereType<Attachment>()
  56. .toList();
  57. }
  58. }