import 'package:flutter/foundation.dart'; @immutable // 标记为不可变类 class ChallengeModel { final int? id; final String title; final String description; final DateTime startDate; final DateTime endDate; final int participants; final bool completed; final String difficulty; final int? remainingDays; // 改为可选字段 const ChallengeModel({ required this.id, required this.title, required this.description, required this.startDate, required this.endDate, required this.participants, required this.completed, required this.difficulty, this.remainingDays, // 可选计算字段 }); int get calculatedRemainingDays => endDate.difference(DateTime.now()).inDays; factory ChallengeModel.fromJson(Map json) { return ChallengeModel( id: json['id'] as int?, title: json['title'] as String, description: json['description'] as String, startDate: DateTime.parse(json['startDate'] as String), endDate: DateTime.parse(json['endDate'] as String), participants: json['participants'] as int, completed: json['completed'] as bool, difficulty: json['difficulty'] as String, ); } /// 转换为JSON Map toJson() => { if (id != null) 'id': id, 'title': title, 'description': description, 'startDate': startDate.toIso8601String(), 'endDate': endDate.toIso8601String(), 'participants': participants, 'completed': completed, 'difficulty': difficulty, }; ChallengeModel copyWith({ int? id, String? title, String? description, DateTime? startDate, DateTime? endDate, int? participants, bool? completed, String? difficulty, }) { return ChallengeModel( id: id ?? this.id, title: title ?? this.title, description: description ?? this.description, startDate: startDate ?? this.startDate, endDate: endDate ?? this.endDate, participants: participants ?? this.participants, completed: completed ?? this.completed, difficulty: difficulty ?? this.difficulty, ); } }