Offline tab as Files view, automatic background sync, sync notifications
Build APK / build (push) Successful in 5m27s

- Offline tab is now FilesView(offline: true) over a FolderBrowser interface
  (FilesController / OfflineController) sharing controls, tiles, thumbnails
- Synced files follow the Files Cache rule (default: refresh every 15 min):
  per-account WorkManager jobs, in-app timer, resume and pull triggers;
  root-etag shortcut skips full walks when nothing changed
- Single sync at a time (shared lock); logging out stops that account's sync
- Sync safety: PROPFIND failures skip the path instead of deleting local files
- Mirror empty folders and remove deleted ones; drop synced paths deleted on
  the server; missing local files are re-downloaded
- Notifications: silent per-account sync notifications, "Background sync
  notifications" setting, audible upload/download completion
- Files refresh in place (no spinner flash); retry after network returns
- Fix sync badges not updating (shared native status stream), "Sync off" on
  launch (eager providers), Files Cache section moved under Device Sync

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-21 18:06:55 -04:00
co-authored by Claude Sonnet 5
parent 49ae712f5e
commit f2bba2914e
38 changed files with 3133 additions and 741 deletions
+64 -65
View File
@@ -8,6 +8,7 @@ import '../providers/settings_controller.dart';
import '../providers/sync_status_controller.dart';
import '../services/sync_service.dart';
import '../theme/app_theme.dart';
import '../widgets/app_tab_view_builder.dart';
import '../widgets/frosted_glass_container.dart';
import '../widgets/seek_bar_painter.dart';
import '../widgets/synced_header_scaffold.dart' show formatQuota;
@@ -254,6 +255,25 @@ class AccountView extends StatelessWidget {
const _DeviceSyncCard(),
const SizedBox(height: 24),
// Files Cache
Text(
'Files Cache',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(
'How often folder listings and synced files refresh from the server',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 10),
const _CacheSettingsCard(),
const SizedBox(height: 24),
// Material You Design Settings
Text(
'Material You Aesthetics',
@@ -443,24 +463,6 @@ class AccountView extends StatelessWidget {
),
const SizedBox(height: 10),
const _MediaPlayerCard(),
const SizedBox(height: 24),
// Files Cache
Text(
'Files Cache',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(
'Reuse a folder\'s listing instead of refetching it on every visit',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 10),
const _CacheSettingsCard(),
],
),
),
@@ -772,8 +774,6 @@ class _DeviceSyncCardState extends State<_DeviceSyncCard> {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final session = context.watch<SessionController>();
final sync = context.watch<SyncStatusController>();
final folders = sync.syncedPaths;
@@ -793,49 +793,37 @@ class _DeviceSyncCardState extends State<_DeviceSyncCard> {
onChanged: sync.setSyncEverything,
),
const Divider(height: 1, indent: 16, endIndent: 16),
if (everything)
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 4),
child: Text(
'Every folder in this account is being synced to this '
'device.',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
ListTile(
leading: const Icon(Icons.offline_pin_rounded),
title: const Text('View offline files'),
subtitle: Text(
everything
? 'Every folder in this account is synced'
: folders.isEmpty
? 'Nothing synced yet'
: '${folders.length} synced folder${folders.length == 1 ? '' : 's'}/file${folders.length == 1 ? '' : 's'}',
),
trailing: const Icon(Icons.chevron_right_rounded),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) =>
Scaffold(body: buildAppTabView(AppTab.offline, ScrollController())),
),
)
else if (folders.isEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 4),
child: Text(
'No folders synced yet - select a folder in Files and use '
'"Sync to device" to mirror it here for offline access.',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
)
else
for (final folder in folders) ...[
ListTile(
leading: const Icon(Icons.sync_rounded),
title: Text(folder),
trailing: IconButton(
icon: const Icon(Icons.close_rounded),
tooltip: 'Stop syncing',
onPressed: () {
sync.removeSyncedPath(folder);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Removed from device sync'),
behavior: SnackBarBehavior.floating,
),
);
},
),
),
const Divider(height: 1, indent: 16, endIndent: 16),
],
),
),
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
secondary: const Icon(Icons.notifications_outlined),
title: const Text('Background sync notifications'),
subtitle: const Text(
'Show a notification when a background sync updates files. '
'Conflicts and "Sync now" always notify.',
),
value: sync.syncNotifications,
onChanged: sync.setSyncNotifications,
),
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
secondary: const Icon(Icons.signal_cellular_alt_rounded),
title: const Text('Sync on cellular'),
@@ -1359,11 +1347,14 @@ class _CacheSettingsCard extends StatelessWidget {
String _description(CachePolicy policy) {
switch (policy) {
case CachePolicy.never:
return 'Every visit to a folder fetches it fresh';
return 'Every visit to a folder fetches it fresh; synced files are '
'checked each time you open the app';
case CachePolicy.interval:
return 'Reuse a folder\'s listing until it\'s a few minutes old';
return 'Reuse a folder\'s listing until it\'s a few minutes old; '
'synced files update in the background on the same schedule';
case CachePolicy.manual:
return 'Reuse a folder\'s listing until you pull to refresh';
return 'Reuse a folder\'s listing until you pull to refresh; synced '
'files only update when you pull down or tap Sync now';
}
}
@@ -1425,6 +1416,14 @@ class _CacheSettingsCard extends StatelessWidget {
onChanged: (value) =>
files.setCacheIntervalMinutes(value.round()),
),
if (files.cacheIntervalMinutes < 15)
Text(
'While the app is closed, synced files refresh at most '
'every 15 min (an Android limit).',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
+235 -65
View File
@@ -1,4 +1,5 @@
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/material.dart';
@@ -53,10 +54,30 @@ class FileViewerScreen extends StatefulWidget {
/// The other items in the same folder/album, so images and videos can be
/// swiped through without leaving the viewer. Non-media items in this list
/// are ignored. If omitted (or the item isn't an image/video), the viewer
/// just shows [item] on its own.
/// just shows [item] on its own. Works the same way whether or not
/// [localPathResolver] is set - swiping through offline media resolves
/// each sibling's local path on demand, exactly like Files/Photos.
final List<NextcloudItem>? siblings;
const FileViewerScreen({super.key, required this.item, this.siblings});
/// When set, every preview (and "open externally") resolves its file
/// from local disk through this instead of fetching from the server -
/// used by the Offline tab, whose whole point is browsing already-
/// downloaded files with no connection. Called once per item actually
/// shown (the initial item and each swiped-to sibling), not just up
/// front. Actions that need a live server (favorite/delete/download-to-
/// device) hide themselves in this mode; Share/Open-externally/Details
/// still work (Share already prefers the local copy when one exists -
/// see `ShareSheet._shareFileDirectly` - and Details' shares/activity/
/// versions tabs degrade the same way any other offline server call
/// does).
final Future<String?> Function(NextcloudItem item)? localPathResolver;
const FileViewerScreen({
super.key,
required this.item,
this.siblings,
this.localPathResolver,
});
/// Opens the viewer with no page transition — media should appear
/// instantly, not fade/zoom in the way MaterialPageRoute normally would.
@@ -65,10 +86,14 @@ class FileViewerScreen extends StatefulWidget {
static Route<void> route({
required NextcloudItem item,
List<NextcloudItem>? siblings,
Future<String?> Function(NextcloudItem item)? localPathResolver,
}) {
return _InstantOpenPageRoute<void>(
pageBuilder: (context) =>
FileViewerScreen(item: item, siblings: siblings),
pageBuilder: (context) => FileViewerScreen(
item: item,
siblings: siblings,
localPathResolver: localPathResolver,
),
);
}
@@ -112,6 +137,8 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
NextcloudItem get _currentItem => _mediaItems[_currentIndex];
bool get _isOffline => widget.localPathResolver != null;
bool get _isPdf => _currentItem.name.toLowerCase().endsWith('.pdf');
bool get _isText => _textPreviewExtensions.contains(
p.extension(_currentItem.name).toLowerCase(),
@@ -173,7 +200,19 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
final item = _currentItem;
setState(() => _isBusy = true);
try {
final path = await _downloadToTemp(session, item);
final path = _isOffline
? await widget.localPathResolver!(item)
: await _downloadToTemp(session, item);
if (path == null) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('This file is no longer available offline'),
),
);
}
return;
}
final result = await OpenFile.open(path);
if (mounted && result.type != ResultType.done) {
ScaffoldMessenger.of(context).showSnackBar(
@@ -371,6 +410,10 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
child: _MediaActionBar(
isFavorite: _currentItem.isFavorite,
isBusy: _isBusy,
// Favorite/delete/download-to-device all need a live
// server - hidden rather than shown-and-failing while
// browsing an already-local file from the Offline tab.
showServerActions: !_isOffline,
opacity: settings.bottomBarOpacity,
blurSigma: settings.bottomBarBlur,
onShare: () => ShareSheet.show(context, _currentItem),
@@ -401,21 +444,59 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
onPageChanged: (index) => setState(() => _currentIndex = index),
itemBuilder: (context, index) {
final mediaItem = _mediaItems[index];
if (mediaItem.type == NextcloudItemType.image) {
return _ImagePreview(
if (!_isOffline) {
if (mediaItem.type == NextcloudItemType.image) {
return _ImagePreview(
key: ValueKey(mediaItem.id),
url: session.service!.fileUrl(mediaItem.path),
headers: session.service!.authHeaders,
);
}
return _VideoPreview(
key: ValueKey(mediaItem.id),
url: session.service!.fileUrl(mediaItem.path),
headers: session.service!.authHeaders,
isActive: index == _currentIndex,
controlsBottomOffset: _controlsVisible ? 108 : 24,
opacity: settings.bottomBarOpacity,
blurSigma: settings.bottomBarBlur,
);
}
return _VideoPreview(
// Offline: each swiped-to item resolves its own local path on
// demand (see FileViewerScreen.localPathResolver's doc comment) -
// this is what makes swiping through offline media behave exactly
// like Files/Photos instead of only ever showing the one item the
// viewer was opened on.
return FutureBuilder<String?>(
key: ValueKey(mediaItem.id),
url: session.service!.fileUrl(mediaItem.path),
headers: session.service!.authHeaders,
isActive: index == _currentIndex,
controlsBottomOffset: _controlsVisible ? 108 : 24,
opacity: settings.bottomBarOpacity,
blurSigma: settings.bottomBarBlur,
future: widget.localPathResolver!(mediaItem),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
final localPath = snapshot.data;
if (localPath == null) {
return Center(
child: Icon(
Icons.cloud_off_rounded,
color: Theme.of(context).colorScheme.onSurfaceVariant,
size: 64,
),
);
}
if (mediaItem.type == NextcloudItemType.image) {
return _ImagePreview(url: null, headers: const {}, localPath: localPath);
}
return _VideoPreview(
url: null,
headers: const {},
localPath: localPath,
isActive: index == _currentIndex,
controlsBottomOffset: _controlsVisible ? 108 : 24,
opacity: settings.bottomBarOpacity,
blurSigma: settings.bottomBarBlur,
);
},
);
},
);
@@ -429,10 +510,18 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
return const SizedBox.shrink();
default:
if (_isPdf) {
return _PdfPreview(item: widget.item, session: session);
return _PdfPreview(
item: widget.item,
session: session,
localPathResolver: widget.localPathResolver,
);
}
if (_isText) {
return _TextPreview(item: widget.item, session: session);
return _TextPreview(
item: widget.item,
session: session,
localPathResolver: widget.localPathResolver,
);
}
return _UnsupportedPreview(
item: widget.item,
@@ -449,6 +538,7 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
class _MediaActionBar extends StatelessWidget {
final bool isFavorite;
final bool isBusy;
final bool showServerActions;
final double opacity;
final double blurSigma;
final VoidCallback onShare;
@@ -461,6 +551,7 @@ class _MediaActionBar extends StatelessWidget {
const _MediaActionBar({
required this.isFavorite,
required this.isBusy,
required this.showServerActions,
required this.opacity,
required this.blurSigma,
required this.onShare,
@@ -493,30 +584,33 @@ class _MediaActionBar extends StatelessWidget {
tooltip: 'Share',
onTap: isBusy ? null : onShare,
),
_ActionIconButton(
icon: isFavorite
? Icons.favorite_rounded
: Icons.favorite_border_rounded,
tooltip: 'Favorite',
color: isFavorite ? Colors.red : null,
onTap: onFavorite,
),
if (showServerActions)
_ActionIconButton(
icon: isFavorite
? Icons.favorite_rounded
: Icons.favorite_border_rounded,
tooltip: 'Favorite',
color: isFavorite ? Colors.red : null,
onTap: onFavorite,
),
_ActionIconButton(
icon: Icons.open_in_new_rounded,
tooltip: 'Open externally',
onTap: isBusy ? null : onOpenExternally,
),
_ActionIconButton(
icon: Icons.download_rounded,
tooltip: 'Download',
onTap: isBusy ? null : onDownload,
),
_ActionIconButton(
icon: Icons.delete_outline_rounded,
tooltip: 'Delete',
color: colorScheme.error,
onTap: isBusy ? null : onDelete,
),
if (showServerActions)
_ActionIconButton(
icon: Icons.download_rounded,
tooltip: 'Download',
onTap: isBusy ? null : onDownload,
),
if (showServerActions)
_ActionIconButton(
icon: Icons.delete_outline_rounded,
tooltip: 'Delete',
color: colorScheme.error,
onTap: isBusy ? null : onDelete,
),
_ActionIconButton(
icon: Icons.info_outline_rounded,
tooltip: 'Details',
@@ -567,10 +661,20 @@ class _ActionIconButton extends StatelessWidget {
}
class _ImagePreview extends StatefulWidget {
final String url;
final String? url;
final Map<String, String> headers;
const _ImagePreview({super.key, required this.url, required this.headers});
/// When set, read the image from this on-disk path instead of [url] -
/// already-resolved by the caller (see
/// `FileViewerScreen.localPathResolver`'s doc comment).
final String? localPath;
const _ImagePreview({
super.key,
required this.url,
required this.headers,
this.localPath,
});
@override
State<_ImagePreview> createState() => _ImagePreviewState();
@@ -646,24 +750,38 @@ class _ImagePreviewState extends State<_ImagePreview>
minScale: 0.8,
maxScale: 5.0,
child: Center(
child: Image.network(
widget.url,
headers: widget.headers,
fit: BoxFit.contain,
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return Center(
child: CircularProgressIndicator(color: colorScheme.primary),
);
},
errorBuilder: (context, error, stack) => Center(
child: Icon(
Icons.broken_image_outlined,
color: colorScheme.onSurfaceVariant,
size: 64,
),
),
),
child: widget.localPath != null
? Image.file(
File(widget.localPath!),
fit: BoxFit.contain,
errorBuilder: (context, error, stack) => Center(
child: Icon(
Icons.broken_image_outlined,
color: colorScheme.onSurfaceVariant,
size: 64,
),
),
)
: Image.network(
widget.url!,
headers: widget.headers,
fit: BoxFit.contain,
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return Center(
child: CircularProgressIndicator(
color: colorScheme.primary,
),
);
},
errorBuilder: (context, error, stack) => Center(
child: Icon(
Icons.broken_image_outlined,
color: colorScheme.onSurfaceVariant,
size: 64,
),
),
),
),
),
),
@@ -672,10 +790,15 @@ class _ImagePreviewState extends State<_ImagePreview>
}
class _VideoPreview extends StatefulWidget {
final String url;
final String? url;
final Map<String, String> headers;
final bool isActive;
/// When set, read the video from this on-disk path instead of [url] -
/// already-resolved by the caller (see
/// `FileViewerScreen.localPathResolver`'s doc comment).
final String? localPath;
/// Distance from the bottom of the screen the transport controls should
/// sit at. Passed in by the parent so the controls can track the floating
/// action bar: resting just above it when visible, sliding down to hug
@@ -691,6 +814,7 @@ class _VideoPreview extends StatefulWidget {
super.key,
required this.url,
required this.headers,
this.localPath,
this.isActive = true,
this.controlsBottomOffset = 24,
this.opacity = 0.55,
@@ -713,10 +837,12 @@ class _VideoPreviewState extends State<_VideoPreview> {
Future<void> _init() async {
try {
final controller = VideoPlayerController.networkUrl(
Uri.parse(widget.url),
httpHeaders: widget.headers,
);
final controller = widget.localPath != null
? VideoPlayerController.file(File(widget.localPath!))
: VideoPlayerController.networkUrl(
Uri.parse(widget.url!),
httpHeaders: widget.headers,
);
await controller.initialize();
if (!mounted) {
controller.dispose();
@@ -973,7 +1099,16 @@ class _PdfPreview extends StatefulWidget {
final NextcloudItem item;
final SessionController session;
const _PdfPreview({required this.item, required this.session});
/// When set, read bytes from the local path it resolves to instead of
/// fetching from the server - see
/// `FileViewerScreen.localPathResolver`'s doc comment.
final Future<String?> Function(NextcloudItem item)? localPathResolver;
const _PdfPreview({
required this.item,
required this.session,
this.localPathResolver,
});
@override
State<_PdfPreview> createState() => _PdfPreviewState();
@@ -991,11 +1126,25 @@ class _PdfPreviewState extends State<_PdfPreview> {
Future<void> _load() async {
try {
final bytes = await widget.session.service!.fetchBytes(widget.item.path);
final Uint8List bytes;
if (widget.localPathResolver != null) {
final localPath = await widget.localPathResolver!(widget.item);
if (localPath == null) {
if (mounted) {
setState(() => _error = 'No longer available offline');
}
return;
}
bytes = await File(localPath).readAsBytes();
} else {
bytes = Uint8List.fromList(
await widget.session.service!.fetchBytes(widget.item.path),
);
}
if (!mounted) return;
setState(() {
_controller = PdfControllerPinch(
document: PdfDocument.openData(Uint8List.fromList(bytes)),
document: PdfDocument.openData(bytes),
);
});
} catch (e) {
@@ -1040,7 +1189,16 @@ class _TextPreview extends StatefulWidget {
final NextcloudItem item;
final SessionController session;
const _TextPreview({required this.item, required this.session});
/// When set, read bytes from the local path it resolves to instead of
/// fetching from the server - see
/// `FileViewerScreen.localPathResolver`'s doc comment.
final Future<String?> Function(NextcloudItem item)? localPathResolver;
const _TextPreview({
required this.item,
required this.session,
this.localPathResolver,
});
@override
State<_TextPreview> createState() => _TextPreviewState();
@@ -1058,7 +1216,19 @@ class _TextPreviewState extends State<_TextPreview> {
Future<void> _load() async {
try {
final bytes = await widget.session.service!.fetchBytes(widget.item.path);
final List<int> bytes;
if (widget.localPathResolver != null) {
final localPath = await widget.localPathResolver!(widget.item);
if (localPath == null) {
if (mounted) {
setState(() => _error = 'No longer available offline');
}
return;
}
bytes = await File(localPath).readAsBytes();
} else {
bytes = await widget.session.service!.fetchBytes(widget.item.path);
}
if (mounted) {
setState(() => _content = utf8.decode(bytes, allowMalformed: true));
}
+180 -254
View File
@@ -1,16 +1,18 @@
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:file_saver/file_saver.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';
import '../models/nextcloud_item.dart';
import '../models/selection_action.dart';
import '../providers/files_controller.dart';
import '../providers/folder_browser.dart';
import '../providers/item_operations.dart';
import '../providers/offline_controller.dart';
import '../providers/pick_controller.dart';
import '../providers/session_controller.dart';
import '../providers/settings_controller.dart';
@@ -19,13 +21,14 @@ import '../services/download_service.dart';
import '../services/share_intent_service.dart';
import '../widgets/breadcrumbs.dart';
import '../widgets/details/details_sheet.dart';
import '../widgets/files_controls_row.dart';
import '../widgets/item_icon.dart';
import '../widgets/manage_synced_folders_sheet.dart';
import '../widgets/media_grid_tile.dart';
import '../widgets/more_tabs_button.dart';
import '../widgets/profile_avatar_button.dart';
import '../widgets/segmented_icon_toggle.dart';
import '../widgets/selectable_thumbnail.dart';
import '../widgets/share_sheet.dart';
import '../widgets/sort_menu_button.dart';
import '../widgets/sticky_header_delegate.dart';
import '../widgets/swipeable_item.dart';
import '../widgets/sync_status_badge.dart';
@@ -34,10 +37,23 @@ import 'file_viewer_screen.dart';
import 'move_copy_destination_picker.dart';
import 'share_upload_view.dart';
/// The Files tab - and, with [offline] set, the Offline tab, which is the
/// same view over the device-sync mirror instead of the server: the Files
/// tab's folders filtered down to what's available offline. The two share
/// every display pref/control, the header, breadcrumbs, list/grid tiles and
/// thumbnails; [offline] only swaps the data source (`FolderBrowser`),
/// reads images from the local file instead of a server preview, and turns
/// off everything that needs the server (selection and its bulk actions,
/// swipe actions, sync badges, the "+" menu, pick mode).
class FilesView extends StatefulWidget {
final ScrollController scrollController;
final bool offline;
const FilesView({super.key, required this.scrollController});
const FilesView({
super.key,
required this.scrollController,
this.offline = false,
});
@override
State<FilesView> createState() => _FilesViewState();
@@ -116,6 +132,35 @@ class _FilesViewState extends State<FilesView>
bool get _isSelecting => _selectedIds.isNotEmpty;
bool get _offline => widget.offline;
/// The folder data source for this tab. Watches the concrete controller
/// (that's what's registered as a provider), then hands it back as the
/// [FolderBrowser] the rest of the view actually needs.
FolderBrowser _browserOf(BuildContext context) => _offline
? context.watch<OfflineController>()
: context.watch<FilesController>();
/// The on-device copy of [item] for the Offline tab; null online, where
/// thumbnails come from server previews instead.
File? _localFileFor(BuildContext context, NextcloudItem item) => _offline
? context.read<OfflineController>().localFileFor(item)
: null;
// (Online only - the Offline tab always reloads on first build, since a
// local listing has no cheap "already loaded" signal.)
// Normally FilesController's own account-activation listener fetches the
// first listing (see FilesController._onAccountActivated) - but the
// bottom nav collapses to just the Offline tab while
// ConnectivityController briefly (mis)reports offline right after a cold
// start, which stops this view (and therefore FilesController, a lazily-
// constructed provider) from ever being built during the window that
// listener fires in. Photos/Favorites already guard against exactly this
// with their own one-shot self-fetch on first build; Files needs the same
// fallback so a folder that's genuinely empty is distinguishable from one
// that just never got its initial fetch.
bool _requestedInitialLoad = false;
@override
void initState() {
super.initState();
@@ -411,14 +456,26 @@ class _FilesViewState extends State<FilesView>
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
// Display prefs (grid/list, filters, sort) live on FilesController for
// both tabs; `browser` is the tab's own folder listing.
final files = context.watch<FilesController>();
final browser = _browserOf(context);
final pathDepth = files.pathStack.length;
if (!_requestedInitialLoad) {
_requestedInitialLoad = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_offline || (browser.items.isEmpty && !browser.isLoading)) {
browser.reload();
}
});
}
final pathDepth = browser.pathStack.length;
final navigatingDeeper = pathDepth > _lastPathDepth;
_lastPathDepth = pathDepth;
final hasBreadcrumbs = files.pathStack.length > 1;
final selectedItems = files.items
final hasBreadcrumbs = browser.pathStack.length > 1;
final selectedItems = browser.items
.where((i) => _selectedIds.contains(i.id))
.toList();
@@ -430,134 +487,20 @@ class _FilesViewState extends State<FilesView>
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 44,
// No persistent hint widget here - instead, a one-shot nudge
// (see _playControlsScrollHint, triggered from initState) just
// scrolls this row a little to the right and back, once, right
// after it first appears. Two static attempts before this -
// fading the controls' own opacity via ShaderMask, then a
// chevron badge overlaid on the edge - both add a
// permanent element competing with the actual controls; a
// motion cue that plays once and gets out of the way reads
// just as clearly without that cost.
child: SingleChildScrollView(
controller: _controlsScrollController,
scrollDirection: Axis.horizontal,
child: Row(
children: [
IconButton(
icon: Icon(
files.filesSortAscending
? Icons.arrow_upward_rounded
: Icons.arrow_downward_rounded,
size: 20,
),
visualDensity: VisualDensity.compact,
tooltip: files.filesSortAscending
? 'Ascending'
: 'Descending',
onPressed: files.toggleFilesSortOrder,
),
// A plain width, not Expanded - this row scrolls
// horizontally now, which gives every control unbounded
// width to lay out in, so a flex child would throw.
SizedBox(
width: 130,
child: SortMenuButton(
field: files.filesSortField,
onChanged: files.setFilesSortField,
),
),
ToggleIconButton(
icon: files.showHiddenFiles
? Icons.visibility_rounded
: Icons.visibility_off_rounded,
isSelected: files.showHiddenFiles,
onTap: () => files.toggleShowHiddenFiles(),
tooltip: 'Show hidden files',
),
const SizedBox(width: 4),
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Symbols.circles_rounded,
isSelected: files.storageScope == StorageScope.cloud,
onTap: () =>
files.setStorageScope(StorageScope.cloud),
tooltip: 'Cloud storage',
),
ToggleIconButton(
icon: Symbols.hard_drive_rounded,
isSelected:
files.storageScope == StorageScope.external,
onTap: () =>
files.setStorageScope(StorageScope.external),
tooltip: 'External storage',
),
],
),
const SizedBox(width: 8),
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Icons.select_all_rounded,
isSelected:
files.filesTypeFilter == FilesTypeFilter.all,
onTap: () =>
files.setFilesTypeFilter(FilesTypeFilter.all),
tooltip: 'Files & folders',
),
ToggleIconButton(
icon: Icons.insert_drive_file_outlined,
isSelected:
files.filesTypeFilter ==
FilesTypeFilter.filesOnly,
onTap: () => files.setFilesTypeFilter(
FilesTypeFilter.filesOnly,
),
tooltip: 'Files only',
),
ToggleIconButton(
icon: Icons.folder_outlined,
isSelected:
files.filesTypeFilter ==
FilesTypeFilter.foldersOnly,
onTap: () => files.setFilesTypeFilter(
FilesTypeFilter.foldersOnly,
),
tooltip: 'Folders only',
),
],
),
const SizedBox(width: 8),
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Icons.view_list_rounded,
isSelected: !files.isGridView,
onTap: () => files.setGridView(false),
tooltip: 'List view',
),
ToggleIconButton(
icon: Icons.grid_view_rounded,
isSelected: files.isGridView,
onTap: () => files.setGridView(true),
tooltip: 'Grid view',
),
],
),
],
),
),
// The scroll-hint nudge (see _playScrollHint) plays on this row
// once, right after it first appears.
FilesControlsRow(
folderPath: browser.currentFolderPath,
showStorageScope: !_offline,
scrollController: _controlsScrollController,
),
if (hasBreadcrumbs) ...[
const SizedBox(height: 10),
SizedBox(
height: 32,
child: Breadcrumbs(
pathStack: files.pathStack,
onTap: (index) => files.navigateToPathIndex(index),
pathStack: browser.pathStack,
onTap: (index) => browser.navigateToPathIndex(index),
),
),
],
@@ -577,12 +520,12 @@ class _FilesViewState extends State<FilesView>
),
),
// Files List / Grid
if (files.isLoading)
if (browser.isLoading)
const SliverFillRemaining(
hasScrollBody: false,
child: Center(child: CircularProgressIndicator()),
)
else if (files.errorMessage != null)
else if (browser.errorMessage != null)
SliverFillRemaining(
hasScrollBody: false,
child: Center(
@@ -598,7 +541,7 @@ class _FilesViewState extends State<FilesView>
),
const SizedBox(height: 16),
Text(
'WebDAV Sync Error',
_offline ? 'Could not read local files' : 'WebDAV Sync Error',
style: theme.textTheme.titleLarge?.copyWith(
color: colorScheme.error,
fontWeight: FontWeight.bold,
@@ -606,7 +549,7 @@ class _FilesViewState extends State<FilesView>
),
const SizedBox(height: 8),
Text(
files.errorMessage!,
browser.errorMessage!,
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
@@ -614,16 +557,16 @@ class _FilesViewState extends State<FilesView>
),
const SizedBox(height: 20),
FilledButton.icon(
onPressed: files.refreshData,
onPressed: browser.reload,
icon: const Icon(Icons.refresh_rounded),
label: const Text('Retry Connection'),
label: Text(_offline ? 'Retry' : 'Retry Connection'),
),
],
),
),
),
)
else if (files.items.isEmpty)
else if (browser.items.isEmpty)
SliverFillRemaining(
hasScrollBody: false,
child: Center(
@@ -631,13 +574,17 @@ class _FilesViewState extends State<FilesView>
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.folder_open_rounded,
_offline
? Icons.offline_pin_outlined
: Icons.folder_open_rounded,
size: 64,
color: colorScheme.outlineVariant,
),
const SizedBox(height: 12),
Text(
'Folder is empty',
_offline && !hasBreadcrumbs
? 'Nothing downloaded yet'
: 'Folder is empty',
style: theme.textTheme.titleMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
@@ -658,14 +605,14 @@ class _FilesViewState extends State<FilesView>
mainAxisSpacing: 12,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = files.items[index];
final item = browser.items[index];
return _FolderEnterAnimation(
key: ValueKey('${files.currentFolderPath}::${item.id}'),
key: ValueKey('${browser.currentFolderPath}::${item.id}'),
index: index,
fromRight: navigatingDeeper,
child: _buildGridCard(context, item),
);
}, childCount: files.items.length),
}, childCount: browser.items.length),
),
)
else
@@ -674,14 +621,14 @@ class _FilesViewState extends State<FilesView>
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final item = files.items[index];
final item = browser.items[index];
return _FolderEnterAnimation(
key: ValueKey('${files.currentFolderPath}::${item.id}'),
key: ValueKey('${browser.currentFolderPath}::${item.id}'),
index: index,
fromRight: navigatingDeeper,
child: _buildListTile(context, item),
);
}, childCount: files.items.length),
}, childCount: browser.items.length),
),
),
@@ -696,23 +643,31 @@ class _FilesViewState extends State<FilesView>
];
return PopScope(
canPop: !_isSelecting && files.pathStack.length <= 1,
canPop: !_isSelecting && browser.pathStack.length <= 1,
onPopInvokedWithResult: (didPop, result) {
if (didPop) return;
if (_isSelecting) {
_clearSelection();
} else {
files.navigateUp();
browser.navigateUp();
}
},
child: SyncedHeaderScaffold(
scrollController: widget.scrollController,
onRefresh: browser.reload,
actions: [
IconButton(
icon: const Icon(Icons.add_rounded),
tooltip: 'New',
onPressed: () => _showCreateMenu(context),
),
if (_offline)
IconButton(
icon: const Icon(Icons.sync_rounded),
tooltip: 'Manage synced folders',
onPressed: () => ManageSyncedFoldersSheet.show(context),
)
else
IconButton(
icon: const Icon(Icons.add_rounded),
tooltip: 'New',
onPressed: () => _showCreateMenu(context),
),
const MoreTabsButton(),
const ProfileAvatarButton(),
],
@@ -815,15 +770,17 @@ class _FilesViewState extends State<FilesView>
) {
final allSynced = items.every((i) => sync.isPathSynced(i.path));
if (allSynced) {
for (final item in items) {
sync.removeSyncedPath(item.path);
}
// Batched (not one removeSyncedPath call per item) so the
// reschedule/native side effects fire once for the whole selection
// instead of racing each other - see addSyncedPaths' doc comment
// for why a per-item loop caused only the first item to actually
// sync.
sync.removeSyncedPaths(items.map((i) => i.path).toList());
} else {
for (final item in items) {
if (!sync.isPathSynced(item.path)) {
sync.addSyncedPath(item.path, isFolder: item.isFolder);
}
}
sync.addSyncedPaths({
for (final item in items)
if (!sync.isPathSynced(item.path)) item.path: item.isFolder,
});
}
_clearSelection();
ScaffoldMessenger.of(context).showSnackBar(
@@ -989,13 +946,15 @@ class _FilesViewState extends State<FilesView>
Widget _buildListTile(BuildContext context, NextcloudItem item) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final files = context.watch<FilesController>();
final browser = _browserOf(context);
final pick = context.watch<PickController>();
final sync = context.watch<SyncStatusController>();
final session = context.watch<SessionController>();
final settings = context.watch<SettingsController>();
final ops = context.read<ItemOperations>();
final isSelected = _selectedIds.contains(item.id);
// Pick mode and selection are server-side features - never on Offline.
final picking = !_offline && pick.isPicking;
// No border radius here — the outer ClipRRect below is the only place
// that rounds this tile's corners. Rounding it here too would give the
@@ -1007,17 +966,17 @@ class _FilesViewState extends State<FilesView>
: colorScheme.surfaceContainerLow,
child: InkWell(
onTap: () {
if (pick.isPicking) {
if (picking) {
_handlePickTap(context, item);
} else if (_isSelecting) {
_toggleSelection(item);
} else if (item.isFolder) {
files.navigateToFolder(item.path);
browser.navigateToFolder(item.path);
} else {
_openFile(context, item);
}
},
onLongPress: pick.isPicking && !pick.pickRequest!.allowMultiple
onLongPress: _offline || (picking && !pick.pickRequest!.allowMultiple)
? null
: () => _toggleSelection(item),
child: Padding(
@@ -1034,18 +993,21 @@ class _FilesViewState extends State<FilesView>
child: ItemThumbnail(
item: item,
service: session.service,
localFile: _localFileFor(context, item),
size: 44,
borderRadius: 12,
iconSize: 22,
),
),
Positioned(
right: -2,
bottom: -2,
child: SyncStatusBadge(
status: sync.syncStatusFor(item),
// Everything on the Offline tab is synced by definition.
if (!_offline)
Positioned(
right: -2,
bottom: -2,
child: SyncStatusBadge(
status: sync.syncStatusFor(item),
),
),
),
],
),
const SizedBox(width: 14),
@@ -1078,7 +1040,7 @@ class _FilesViewState extends State<FilesView>
),
);
final content = _isSelecting || pick.isPicking
final content = _isSelecting || picking || _offline
? card
: SwipeableItem(
itemKey: ValueKey('file-${item.id}'),
@@ -1111,14 +1073,19 @@ class _FilesViewState extends State<FilesView>
}
Widget _buildGridCard(BuildContext context, NextcloudItem item) {
final files = context.watch<FilesController>();
final browser = _browserOf(context);
final pick = context.watch<PickController>();
final sync = context.watch<SyncStatusController>();
final isSelected = _selectedIds.contains(item.id);
final isMedia =
(item.type == NextcloudItemType.image ||
item.type == NextcloudItemType.video) &&
item.previewUrl != null;
final picking = !_offline && pick.isPicking;
// Offline reads the image straight from the local mirror; videos have
// no local thumbnail (that would need a frame-extraction plugin), so
// they fall through to the plain icon card there.
final isMedia = _offline
? item.type == NextcloudItemType.image
: (item.type == NextcloudItemType.image ||
item.type == NextcloudItemType.video) &&
item.previewUrl != null;
return Material(
color: Theme.of(context).colorScheme.surfaceContainerLow,
@@ -1126,17 +1093,17 @@ class _FilesViewState extends State<FilesView>
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () {
if (pick.isPicking) {
if (picking) {
_handlePickTap(context, item);
} else if (_isSelecting) {
_toggleSelection(item);
} else if (item.isFolder) {
files.navigateToFolder(item.path);
browser.navigateToFolder(item.path);
} else {
_openFile(context, item);
}
},
onLongPress: pick.isPicking && !pick.pickRequest!.allowMultiple
onLongPress: _offline || (picking && !pick.pickRequest!.allowMultiple)
? null
: () => _toggleSelection(item),
child: Stack(
@@ -1148,92 +1115,36 @@ class _FilesViewState extends State<FilesView>
? _buildMediaGridContent(context, item)
: _buildPlainGridContent(context, item),
),
Positioned(
right: 6,
bottom: 6,
child: SyncStatusBadge(status: sync.syncStatusFor(item)),
),
if (!_offline)
Positioned(
right: 6,
bottom: 6,
child: SyncStatusBadge(status: sync.syncStatusFor(item)),
),
],
),
),
);
}
/// Grid content for images/videos: the actual preview fills the whole
/// card as a background, with the name/size legible over a bottom scrim
/// — matching a Google Photos-style grid instead of a small icon badge.
/// Grid content for images/videos - see [MediaGridTile].
Widget _buildMediaGridContent(BuildContext context, NextcloudItem item) {
final session = context.watch<SessionController>();
final theme = Theme.of(context);
final localFile = _localFileFor(context, item);
return LayoutBuilder(
builder: (context, constraints) {
final cachePixels =
(constraints.maxWidth * MediaQuery.of(context).devicePixelRatio)
.round();
return Stack(
fit: StackFit.expand,
children: [
Image.network(
item.previewUrl!,
headers: session.service?.authHeaders,
fit: BoxFit.cover,
cacheWidth: cachePixels,
cacheHeight: cachePixels,
filterQuality: FilterQuality.low,
gaplessPlayback: true,
errorBuilder: (ctx, err, stack) =>
_buildPlainGridContent(context, item),
),
if (item.type == NextcloudItemType.video)
const Center(
child: Icon(
Icons.play_circle_fill_rounded,
color: Colors.white,
size: 36,
),
return MediaGridTile(
item: item,
imageBuilder: (cachePixels) => ResizeImage(
localFile != null
? FileImage(localFile)
: NetworkImage(
item.previewUrl!,
headers: session.service?.authHeaders,
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Container(
padding: const EdgeInsets.fromLTRB(10, 20, 10, 8),
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, Colors.black87],
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleSmall?.copyWith(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 12,
),
),
Text(
formatBytes(item.size),
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.white70,
fontSize: 10,
),
),
],
),
),
),
],
);
},
width: cachePixels,
height: cachePixels,
),
fallbackBuilder: (ctx) => _buildPlainGridContent(ctx, item),
);
}
@@ -1287,6 +1198,21 @@ class _FilesViewState extends State<FilesView>
}
void _openFile(BuildContext context, NextcloudItem item) {
if (_offline) {
// Same in-app viewer (including swiping between the folder's media),
// just reading from disk instead of the server - see
// `FileViewerScreen.localPathResolver`'s doc comment.
final offline = context.read<OfflineController>();
Navigator.push(
context,
FileViewerScreen.route(
item: item,
siblings: offline.items,
localPathResolver: offline.localPathFor,
),
);
return;
}
final files = context.read<FilesController>();
Navigator.push(
context,