challenge_model.dart 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import 'package:flutter/foundation.dart';
  2. @immutable // 标记为不可变类
  3. class ChallengeModel {
  4. final int? id;
  5. final String title;
  6. final String description;
  7. final DateTime startDate;
  8. final DateTime endDate;
  9. final int participants;
  10. final bool completed;
  11. final String difficulty;
  12. final int? remainingDays; // 改为可选字段
  13. const ChallengeModel({
  14. required this.id,
  15. required this.title,
  16. required this.description,
  17. required this.startDate,
  18. required this.endDate,
  19. required this.participants,
  20. required this.completed,
  21. required this.difficulty,
  22. this.remainingDays, // 可选计算字段
  23. });
  24. int get calculatedRemainingDays => endDate.difference(DateTime.now()).inDays;
  25. factory ChallengeModel.fromJson(Map<String, dynamic> json) {
  26. return ChallengeModel(
  27. id: json['id'] as int?,
  28. title: json['title'] as String,
  29. description: json['description'] as String,
  30. startDate: DateTime.parse(json['startDate'] as String),
  31. endDate: DateTime.parse(json['endDate'] as String),
  32. participants: json['participants'] as int,
  33. completed: json['completed'] as bool,
  34. difficulty: json['difficulty'] as String,
  35. );
  36. }
  37. /// 转换为JSON
  38. Map<String, dynamic> toJson() => {
  39. if (id != null) 'id': id,
  40. 'title': title,
  41. 'description': description,
  42. 'startDate': startDate.toIso8601String(),
  43. 'endDate': endDate.toIso8601String(),
  44. 'participants': participants,
  45. 'completed': completed,
  46. 'difficulty': difficulty,
  47. };
  48. ChallengeModel copyWith({
  49. int? id,
  50. String? title,
  51. String? description,
  52. DateTime? startDate,
  53. DateTime? endDate,
  54. int? participants,
  55. bool? completed,
  56. String? difficulty,
  57. }) {
  58. return ChallengeModel(
  59. id: id ?? this.id,
  60. title: title ?? this.title,
  61. description: description ?? this.description,
  62. startDate: startDate ?? this.startDate,
  63. endDate: endDate ?? this.endDate,
  64. participants: participants ?? this.participants,
  65. completed: completed ?? this.completed,
  66. difficulty: difficulty ?? this.difficulty,
  67. );
  68. }
  69. }