document_provider.dart 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import 'package:flutter/foundation.dart';
  2. import '../models/document.dart';
  3. import '../services/mock_data_service.dart';
  4. /// 文档状态管理
  5. class DocumentProvider with ChangeNotifier {
  6. List<Document> _documents = [];
  7. Document? _selectedDocument;
  8. bool _loading = false;
  9. List<Document> get documents => _documents;
  10. Document? get selectedDocument => _selectedDocument;
  11. bool get loading => _loading;
  12. DocumentProvider() {
  13. loadDocuments();
  14. }
  15. /// 加载文档列表
  16. Future<void> loadDocuments() async {
  17. _loading = true;
  18. notifyListeners();
  19. // 模拟网络请求
  20. await Future.delayed(const Duration(milliseconds: 500));
  21. _documents = MockDataService.getMockDocuments();
  22. _loading = false;
  23. notifyListeners();
  24. }
  25. /// 选择文档
  26. void selectDocument(Document document) {
  27. _selectedDocument = document;
  28. notifyListeners();
  29. }
  30. /// 添加文档
  31. void addDocument(Document document) {
  32. _documents.insert(0, document);
  33. notifyListeners();
  34. }
  35. /// 更新文档
  36. void updateDocument(Document document) {
  37. final index = _documents.indexWhere((d) => d.id == document.id);
  38. if (index != -1) {
  39. _documents[index] = document;
  40. notifyListeners();
  41. }
  42. }
  43. /// 删除文档
  44. void deleteDocument(String id) {
  45. _documents.removeWhere((d) => d.id == id);
  46. if (_selectedDocument?.id == id) {
  47. _selectedDocument = null;
  48. }
  49. notifyListeners();
  50. }
  51. /// 根据ID获取文档
  52. Document? getDocumentById(String id) {
  53. try {
  54. return _documents.firstWhere((d) => d.id == id);
  55. } catch (e) {
  56. return null;
  57. }
  58. }
  59. }