Newer
Older
MiniTias / lib / providers / gallery_provider.dart
import 'dart:io';

import 'package:flutter/foundation.dart';

/// 画像一覧の取得・キャッシュ・削除操作を管理する.
class GalleryProvider extends ChangeNotifier {
  static const _basePath = '/storage/emulated/0/Pictures/MiniTIAS';

  List<File> _images = [];
  bool _isLoading = false;

  List<File> get images => _images;
  bool get isLoading => _isLoading;

  /// Pictures/MiniTIAS/ 内の PNG ファイルを取得し,新しい順に並べる.
  Future<void> loadImages() async {
    _isLoading = true;
    notifyListeners();

    try {
      final directory = Directory(_basePath);
      if (!await directory.exists()) {
        _images = [];
      } else {
        final files = await directory
            .list()
            .where(
              (entity) =>
                  entity is File && entity.path.toLowerCase().endsWith('.png'),
            )
            .cast<File>()
            .toList();

        // 更新日時の新しい順にソート
        files.sort((a, b) {
          final aStat = a.statSync();
          final bStat = b.statSync();
          return bStat.modified.compareTo(aStat.modified);
        });

        _images = files;
      }
    } catch (e) {
      debugPrint('画像一覧の取得に失敗: $e');
      _images = [];
    }

    _isLoading = false;
    notifyListeners();
  }

  /// 指定したファイルを削除し,一覧から除去する.
  Future<bool> deleteImage(File file) async {
    try {
      if (await file.exists()) {
        await file.delete();
      }
      // 削除成功後にのみ一覧から除去
      if (!await file.exists()) {
        _images.remove(file);
        notifyListeners();
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('画像の削除に失敗: $e');
      return false;
    }
  }
}