Gallery/lib/image_grid.dart
2022-09-29 20:32:52 +02:00

120 lines
4.1 KiB
Dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'data_provider/data_provider.dart';
import 'full_screen_image_view.dart';
import 'image_tile.dart';
class ImageGrid extends StatefulWidget {
const ImageGrid({Key? key, required this.dProvider}) : super(key: key);
final DataProvider dProvider;
@override
State<ImageGrid> createState() => _ImageGridState();
}
class _ImageGridState extends State<ImageGrid> {
final ScrollController _controller = ScrollController();
late Future<Folder> folder = widget.dProvider.listOfFiles();
@override
void didUpdateWidget(ImageGrid oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.dProvider != widget.dProvider) {
folder = widget.dProvider.listOfFiles();
}
}
@override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
return FutureBuilder(
future: folder,
builder: (context, AsyncSnapshot<Folder> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData && snapshot.data != null) {
final Folder data = snapshot.data!;
return GridView.builder(
controller: _controller,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisSpacing: 0,
mainAxisSpacing: 0,
crossAxisCount:
Platform.isAndroid ? width ~/ 100 : width ~/ 300,
),
itemCount: data.items.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
return ImageTile(
child: Icon(Icons.arrow_back,
size: Platform.isAndroid ? 64 : 142),
onClick: () {
setState(() {
folder = widget.dProvider.listOfFiles(uri: data.parent);
});
},
);
}
final elem = data.items[index - 1];
return ImageTile(
dtaProvider: widget.dProvider,
imageUri: elem.isFolder ? null : elem.uri,
onClick: () {
if (elem.isFolder) {
setState(() {
folder = widget.dProvider.listOfFiles(uri: elem.uri);
});
_controller.jumpTo(.0);
} else {
Navigator.push(
context,
MaterialPageRoute(builder: (context) {
final d = data.items
.where((element) => !element.isFolder)
.toList(growable: false);
// check how many folders are before index and subtract it
final newidx = index -
data.items
.getRange(0, index)
.where((element) => element.isFolder)
.length;
return FullScreenImageView(
provider: widget.dProvider,
items: d,
idx: newidx,
);
}),
);
}
},
child: elem.isFolder
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.folder_open,
size: Platform.isAndroid ? 64 : 142),
Text(elem.name)
],
)
: null);
},
);
} else if (snapshot.hasError) {
return Text("Error loading files: ${snapshot.error}");
}
}
return const CircularProgressIndicator(
strokeWidth: 3,
);
},
);
}
}