99 lines
2.8 KiB
Dart
99 lines
2.8 KiB
Dart
import 'dart:io';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'package:permission_handler/permission_handler.dart';
|
|
import 'package:open_filex/open_filex.dart';
|
|
|
|
class PdfListScreen extends StatefulWidget {
|
|
const PdfListScreen({super.key});
|
|
|
|
@override
|
|
State<PdfListScreen> createState() => _PdfListScreenState();
|
|
}
|
|
|
|
class _PdfListScreenState extends State<PdfListScreen> {
|
|
List<FileSystemEntity> _pdfFiles = [];
|
|
bool _loading = true;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_fetchPdfFiles();
|
|
}
|
|
|
|
Future<void> _fetchPdfFiles() async {
|
|
// Request storage permission
|
|
final status = await Permission.storage.request();
|
|
if (!status.isGranted) {
|
|
setState(() {
|
|
_loading = false;
|
|
});
|
|
return;
|
|
}
|
|
|
|
// Prefer to look in the Downloads folder if available
|
|
Directory? downloadsDir;
|
|
if (Platform.isAndroid) {
|
|
downloadsDir = await getExternalStorageDirectory();
|
|
// The Downloads folder may be a subdirectory; adjust as needed
|
|
if (downloadsDir != null) {
|
|
downloadsDir = Directory('${downloadsDir.path}/Download');
|
|
}
|
|
} else if (Platform.isIOS) {
|
|
downloadsDir = await getApplicationDocumentsDirectory();
|
|
} else {
|
|
downloadsDir = await getApplicationDocumentsDirectory();
|
|
}
|
|
|
|
if (downloadsDir == null || !await downloadsDir.exists()) {
|
|
setState(() {
|
|
_loading = false;
|
|
});
|
|
return;
|
|
}
|
|
|
|
final files = downloadsDir
|
|
.listSync()
|
|
.where((f) => f.path.toLowerCase().endsWith('.pdf'))
|
|
.toList();
|
|
|
|
setState(() {
|
|
_pdfFiles = files;
|
|
_loading = false;
|
|
});
|
|
}
|
|
|
|
void _openFile(FileSystemEntity file) async {
|
|
final result = await OpenFilex.open(file.path);
|
|
if (result.type != ResultType.success) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(content: Text('Could not open ${file.path}')),
|
|
);
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: const Text('PDF ファイル一覧'),
|
|
),
|
|
body: _loading
|
|
? const Center(child: CircularProgressIndicator())
|
|
: _pdfFiles.isEmpty
|
|
? const Center(child: Text('PDF ファイルが見つかりません。'))
|
|
: ListView.builder(
|
|
itemCount: _pdfFiles.length,
|
|
itemBuilder: (context, index) {
|
|
final file = _pdfFiles[index];
|
|
final fileName = file.path.split(Platform.pathSeparator).last;
|
|
return ListTile(
|
|
leading: const Icon(Icons.picture_as_pdf),
|
|
title: Text(fileName),
|
|
onTap: () => _openFile(file),
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
}
|