Files
ai_english/client/lib/features/home/providers/learning_progress_provider.dart
2025-11-17 14:09:17 +08:00

107 lines
3.0 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/learning_progress_model.dart';
import '../services/learning_progress_service.dart';
/// 学习进度状态
class LearningProgressState {
final List<LearningProgress> progressList;
final bool isLoading;
final String? error;
LearningProgressState({
this.progressList = const [],
this.isLoading = false,
this.error,
});
LearningProgressState copyWith({
List<LearningProgress>? progressList,
bool? isLoading,
String? error,
}) {
return LearningProgressState(
progressList: progressList ?? this.progressList,
isLoading: isLoading ?? this.isLoading,
error: error,
);
}
}
/// 学习进度Notifier
class LearningProgressNotifier extends StateNotifier<LearningProgressState> {
final LearningProgressService _service = LearningProgressService();
LearningProgressNotifier() : super(LearningProgressState());
/// 加载学习进度
Future<void> loadLearningProgress() async {
state = state.copyWith(isLoading: true, error: null);
try {
final response = await _service.getUserLearningProgress();
if (response.success && response.data != null) {
state = state.copyWith(
progressList: response.data!,
isLoading: false,
);
} else {
state = state.copyWith(
isLoading: false,
error: response.message,
);
}
} catch (e) {
state = state.copyWith(
isLoading: false,
error: '加载学习进度失败: $e',
);
}
}
/// 刷新学习进度(强制重新加载,不使用缓存)
Future<void> refreshLearningProgress() async {
state = state.copyWith(isLoading: true, error: null);
try {
// 强制重新加载,传入不同的时间戳来绕过缓存
final response = await _service.getUserLearningProgress();
if (response.success && response.data != null) {
print('=== 刷新学习进度成功 ===');
print('数据条数: ${response.data!.length}');
state = state.copyWith(
progressList: response.data!,
isLoading: false,
);
} else {
state = state.copyWith(
isLoading: false,
error: response.message,
);
}
} catch (e) {
print('刷新学习进度失败: $e');
state = state.copyWith(
isLoading: false,
error: '刷新学习进度失败: $e',
);
}
}
}
/// 学习进度Provider
final learningProgressProvider = StateNotifierProvider<LearningProgressNotifier, LearningProgressState>(
(ref) => LearningProgressNotifier(),
);
/// 学习进度列表Provider便捷访问
final learningProgressListProvider = Provider<List<LearningProgress>>((ref) {
return ref.watch(learningProgressProvider).progressList;
});
/// 学习进度加载状态Provider
final learningProgressLoadingProvider = Provider<bool>((ref) {
return ref.watch(learningProgressProvider).isLoading;
});