Replace receive_sharing_intent; add background upload service; fix add-account login page

Sharing a large file to Noo used to black-screen and silently kick back
to the home screen: receive_sharing_intent copies the entire shared file
into the cache dir synchronously on the main thread before Flutter even
renders, which Android's watchdog eventually kills. Replaced with
hand-rolled handling in MainActivity.kt that only ever reads cheap Uri
metadata up front (ShareIntentService), so the destination picker always
appears instantly regardless of file size.

The destination picker (ShareUploadView) now mirrors the Files tab's own
controls/filters/listing instead of a bare folder list, and the actual
prepare+upload is handed off to ShareUploadService.kt, a real Android
foreground service with a single cancellable progress notification for
the whole batch - this survives the app being closed right after the
user confirms a destination, the same guarantee a file-manager app's own
upload notification gives.

Also fixes the "add another account" login page: it used to open in
url_launcher's bare inAppWebView, which has no close button and can hide
the status bar. LoginWebViewView is a real screen this app owns instead
(package:webview_flutter), with a normal AppBar/close button/safe area,
and can now auto-close itself on successful login.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-16 23:33:55 -04:00
co-authored by Claude Sonnet 5
parent 453aff983a
commit bcc18a7060
13 changed files with 1164 additions and 181 deletions
+14 -21
View File
@@ -2,9 +2,9 @@ import 'dart:async';
import 'package:dynamic_color/dynamic_color.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
import 'models/app_tab.dart';
import 'providers/server_provider.dart';
import 'services/share_intent_service.dart';
import 'theme/app_theme.dart';
import 'views/lock_screen_view.dart';
import 'views/login_view.dart';
@@ -112,7 +112,7 @@ class MainShellView extends StatefulWidget {
class _MainShellViewState extends State<MainShellView> {
late AppTab _currentTab;
late final Map<AppTab, ScrollController> _scrollControllers;
StreamSubscription<List<SharedMediaFile>>? _shareSub;
StreamSubscription<List<SharedFileRef>>? _shareSub;
@override
void initState() {
@@ -126,29 +126,22 @@ class _MainShellViewState extends State<MainShellView> {
_currentTab = context.read<ServerProvider>().defaultTab;
// Handles both a cold start via another app's "Share to..." sheet
// (getInitialMedia) and a share arriving while the app is already
// running (getMediaStream) - the plugin guarantees the stream doesn't
// re-emit whatever getInitialMedia already returned.
ReceiveSharingIntent.instance.getInitialMedia().then(_handleSharedFiles);
_shareSub = ReceiveSharingIntent.instance.getMediaStream().listen(
_handleSharedFiles,
);
// (getInitialShare) and a share arriving while the app is already
// running (onNewShare). See MainActivity.kt's doc comment for why this
// is hand-rolled instead of the receive_sharing_intent plugin - in
// short, this only ever fetches cheap Uri metadata here, never a
// file's actual bytes, so a large shared file can't block startup.
ShareIntentService.getInitialShare().then(_handleSharedFiles);
_shareSub = ShareIntentService.onNewShare.listen(_handleSharedFiles);
}
void _handleSharedFiles(List<SharedMediaFile> files) {
final uploadable = files
.where(
(f) =>
f.type != SharedMediaType.text && f.type != SharedMediaType.url,
)
.toList();
if (uploadable.isEmpty) return;
ReceiveSharingIntent.instance.reset();
void _handleSharedFiles(List<SharedFileRef> files) {
if (files.isEmpty) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => ShareUploadView(files: uploadable)),
);
Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => ShareUploadView(files: files)));
});
}
+36 -14
View File
@@ -725,20 +725,39 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
final init = await LoginFlowService.initiate(serverUrl);
_pendingLoginUrl = init.loginUrl;
// Chrome Custom Tabs (inAppBrowserView): real Chrome, so the saved
// passwords/autofill service works normally, unlike Flutter's own
// embedded web view. The tradeoff is that - like Login Flow v2's
// grant page itself, which never redirects back into the app on its
// own (unlike the old nc:// Flow v1) - a Custom Tab belongs to
// Chrome's own task, not ours, so we have no way to close it
// automatically once polling below detects success; the user has to
// switch back manually, same as with the external browser.
final opened = await launchUrl(
init.loginUrl,
mode: LaunchMode.inAppBrowserView,
);
if (!opened) {
throw Exception('Could not open the browser for login.');
// Chrome Custom Tabs (inAppBrowserView) for the first/only login:
// real Chrome, so the saved passwords/autofill service works
// normally, unlike Flutter's own embedded web view. The tradeoff is
// that - like Login Flow v2's grant page itself, which never
// redirects back into the app on its own (unlike the old nc://
// Flow v1) - a Custom Tab belongs to Chrome's own task, not ours, so
// we have no way to close it automatically once polling below
// detects success; the user has to switch back manually, same as
// with the external browser.
//
// Adding another account instead shows the login page in
// LoginWebViewView, a real screen this app owns (pushed by LoginView
// once loginFlowStatus flips to awaitingBrowser below), backed by
// Flutter's own WebView rather than a Custom Tab. Two reasons, not
// just one: (1) a Custom Tab shares Chrome's actual browser
// profile/cookie jar, so if the user is still logged into the first
// account on the Nextcloud web UI in Chrome, it would silently reuse
// that session and authorize the wrong account instead of prompting
// fresh credentials; (2) url_launcher's own LaunchMode.inAppWebView
// is a bare native WebView Activity with no chrome of its own - no
// close button, and on at least some devices it draws edge-to-edge
// and hides the status bar. Owning the screen ourselves fixes both:
// isolated cookies, plus a normal AppBar/close button/safe area, and
// as a bonus we CAN close it automatically on success (LoginWebView
// View watches loginFlowStatus itself), unlike the Custom Tab case.
if (!addAccount) {
final opened = await launchUrl(
init.loginUrl,
mode: LaunchMode.inAppBrowserView,
);
if (!opened) {
throw Exception('Could not open the browser for login.');
}
}
_loginFlowStatus = LoginFlowStatus.awaitingBrowser;
@@ -790,6 +809,9 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
}
}
// Only relevant to the first/only-login Chrome Custom Tab path - the
// add-account LoginWebViewView is a normal pushed screen the user can't
// lose track of, so it has no equivalent "reopen" need.
Future<void> reopenLoginBrowser() async {
if (_pendingLoginUrl != null) {
await launchUrl(_pendingLoginUrl!, mode: LaunchMode.inAppBrowserView);
+61
View File
@@ -0,0 +1,61 @@
import 'package:flutter/services.dart';
/// A file shared to Noo from another app's "Share to..." sheet, before its
/// bytes have been touched - just the `content://` Uri and whatever cheap
/// metadata Android will hand over without reading the file itself.
class SharedFileRef {
final String uri;
final String name;
final String? mimeType;
final int? size;
const SharedFileRef({
required this.uri,
required this.name,
this.mimeType,
this.size,
});
factory SharedFileRef.fromMap(Map<dynamic, dynamic> map) {
return SharedFileRef(
uri: map['uri'] as String,
name: map['name'] as String? ?? 'shared_file',
mimeType: map['mimeType'] as String?,
size: (map['size'] as num?)?.toInt(),
);
}
}
/// Talks to `MainActivity.kt`'s hand-rolled share-intent handling (see its
/// doc comment for why this isn't the receive_sharing_intent plugin): it
/// only ever exposes cheap Uri metadata up front. Actually reading a shared
/// file's bytes - preparing and uploading it - is [UploadService]'s job
/// (`ShareUploadService.kt`'s Android foreground service), not this one.
class ShareIntentService {
static const _methodChannel = MethodChannel('dev.ayushya.noo/share_intent');
static const _newShareChannel = EventChannel(
'dev.ayushya.noo/share_intent/new',
);
/// Whatever was shared to launch the app cold (empty if it was launched
/// normally, not via a share).
static Future<List<SharedFileRef>> getInitialShare() async {
final result = await _methodChannel.invokeMethod<List<dynamic>>(
'getInitialShare',
);
return (result ?? [])
.cast<Map<dynamic, dynamic>>()
.map(SharedFileRef.fromMap)
.toList();
}
/// Emits whenever another share arrives while the app is already running.
static Stream<List<SharedFileRef>> get onNewShare {
return _newShareChannel.receiveBroadcastStream().map((event) {
return (event as List<dynamic>)
.cast<Map<dynamic, dynamic>>()
.map(SharedFileRef.fromMap)
.toList();
});
}
}
+42
View File
@@ -0,0 +1,42 @@
import 'dart:convert';
import 'package:flutter/services.dart';
import '../providers/server_provider.dart';
import 'share_intent_service.dart';
/// Hands a "Share to Noo" upload off to `ShareUploadService.kt`'s Android
/// foreground service, which does the actual prepare+upload entirely on its
/// own from there - including surviving the app being closed - with a
/// single cancellable progress notification for the whole batch. See that
/// service's doc comment for why this isn't done in Dart/Dio: a Dart
/// isolate doesn't keep running once the Flutter engine is gone, only a
/// real Android Service does.
class UploadService {
static const _channel = MethodChannel('dev.ayushya.noo/upload_service');
/// Starts uploading [files] into the active account's current folder.
/// Fire-and-forget from Dart's perspective - once this returns, the
/// service owns the rest and reports progress/completion/cancellation
/// through its own notification, not back to the app.
static Future<void> startUpload(
ServerProvider provider,
List<SharedFileRef> files,
) async {
final service = provider.service;
final authHeader = service?.authHeaders['Authorization'];
if (service == null || authHeader == null) {
throw Exception('Not logged in.');
}
final filesJson = jsonEncode(
files.map((f) => {'uri': f.uri, 'name': f.name, 'size': f.size}).toList(),
);
await _channel.invokeMethod('startUpload', {
'files': filesJson,
'serverUrl': provider.serverUrl,
'username': provider.username,
'authHeader': authHeader,
'remoteFolder': provider.currentFolderPath,
});
}
}
+39 -5
View File
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/saved_account.dart';
import '../providers/server_provider.dart';
import 'login_webview_view.dart';
class LoginView extends StatefulWidget {
/// True when this is pushed from Settings ("Add account") on top of an
@@ -21,6 +22,7 @@ class _LoginViewState extends State<LoginView> {
final _urlController = TextEditingController();
String? _originalActiveAccountId;
bool _popped = false;
bool _webViewPushed = false;
@override
void initState() {
@@ -67,6 +69,27 @@ class _LoginViewState extends State<LoginView> {
});
}
// The add-account flow shows its login page in LoginWebViewView (a
// real pushed screen, not a Custom Tab - see ServerProvider.
// startLoginFlow's doc comment for why) rather than this view's own
// _WaitingForBrowser, so push it the moment there's a URL to show.
// _webViewPushed resets once that route pops (cancelled or done) so a
// retry after cancelling pushes it again.
if (widget.isAddingAccount &&
!_webViewPushed &&
isAwaitingBrowser &&
provider.pendingLoginUrl != null) {
_webViewPushed = true;
final url = provider.pendingLoginUrl!;
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (!mounted) return;
await Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => LoginWebViewView(url: url)));
_webViewPushed = false;
});
}
final body = Scaffold(
appBar: widget.isAddingAccount
? AppBar(title: const Text('Add Account'))
@@ -78,7 +101,7 @@ class _LoginViewState extends State<LoginView> {
padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 440),
child: isAwaitingBrowser
child: isAwaitingBrowser && !widget.isAddingAccount
? _WaitingForBrowser(
onCancel: () => provider.cancelLoginFlow(),
onReopenBrowser: provider.reopenLoginBrowser,
@@ -120,7 +143,10 @@ class _LoginViewState extends State<LoginView> {
_ServerForm(
formKey: _formKey,
urlController: _urlController,
isLoading: isInitiating || provider.isLoading,
isLoading:
isInitiating ||
provider.isLoading ||
(widget.isAddingAccount && isAwaitingBrowser),
errorMessage:
provider.loginFlowStatus == LoginFlowStatus.error
? provider.errorMessage
@@ -182,10 +208,18 @@ class _ServerForm extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
// Same monochrome-tinted treatment as the splash/lock screens
// (see main.dart's _SplashView) - the asset is a plain white
// silhouette on transparent, meant to be recolored rather than
// shown as-is. Used everywhere the app shows its own icon
// in-app, rather than the full-color launcher icon.
child: ColorFiltered(
colorFilter: ColorFilter.mode(
Theme.of(context).colorScheme.onSurface,
BlendMode.srcIn,
),
child: Image.asset(
'assets/icon/app_icon.png',
'assets/icon/app_icon_monochrome.png',
width: 80,
height: 80,
),
+92
View File
@@ -0,0 +1,92 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../providers/server_provider.dart';
/// The "add another account" Login Flow v2 page, rendered in Flutter's own
/// WebView rather than url_launcher's `LaunchMode.inAppWebView` - that mode
/// hosts a bare native WebView Activity with no chrome of its own: no close
/// button, and on at least some devices it draws edge-to-edge and hides the
/// status bar with no way back short of the OS back gesture. A normal
/// Scaffold/AppBar here gets the status bar/safe-area handling and a close
/// button for free, exactly like every other screen in the app.
///
/// See ServerProvider.startLoginFlow's doc comment for why the add-account
/// flow uses an embedded WebView (isolated cookies) instead of a Chrome
/// Custom Tab at all.
class LoginWebViewView extends StatefulWidget {
final Uri url;
const LoginWebViewView({super.key, required this.url});
@override
State<LoginWebViewView> createState() => _LoginWebViewViewState();
}
class _LoginWebViewViewState extends State<LoginWebViewView> {
late final WebViewController _controller;
bool _pageLoading = true;
bool _popped = false;
@override
void initState() {
super.initState();
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(
onPageStarted: (_) {
if (mounted) setState(() => _pageLoading = true);
},
onPageFinished: (_) {
if (mounted) setState(() => _pageLoading = false);
},
),
)
..loadRequest(widget.url);
}
void _cancel() {
context.read<ServerProvider>().cancelLoginFlow();
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
final provider = context.watch<ServerProvider>();
// The login flow finished (success or error) or was cancelled
// elsewhere - close this screen automatically rather than leaving it
// sitting open over a flow that's no longer awaiting the browser.
if (!_popped &&
provider.loginFlowStatus != LoginFlowStatus.awaitingBrowser) {
_popped = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) Navigator.of(context).pop();
});
}
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) {
if (!didPop) _cancel();
},
child: Scaffold(
appBar: AppBar(
title: const Text('Add Account'),
leading: IconButton(
icon: const Icon(Icons.close_rounded),
tooltip: 'Cancel',
onPressed: _cancel,
),
),
body: Stack(
children: [
WebViewWidget(controller: _controller),
if (_pageLoading) const LinearProgressIndicator(),
],
),
),
);
}
}
+345 -115
View File
@@ -1,17 +1,29 @@
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:intl/intl.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:provider/provider.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
import '../models/app_tab.dart';
import '../models/nextcloud_item.dart';
import '../providers/server_provider.dart';
import '../services/share_intent_service.dart';
import '../services/upload_service.dart';
import '../widgets/breadcrumbs.dart';
import '../widgets/item_icon.dart';
import '../widgets/segmented_icon_toggle.dart';
import '../widgets/sort_menu_button.dart';
import '../widgets/synced_header_scaffold.dart' show formatBytes;
/// Shown when another app shares one or more files to Noo (Android's
/// "Share to..." sheet). Lets the user browse to a destination folder, then
/// uploads every shared file into it via the same WebDAV upload path as the
/// Files tab's own "Upload File" action.
/// "Share to..." sheet). Lets the user browse to a destination folder,
/// mirroring the Files tab's own controls/filters/listing so this feels
/// like the same browser rather than a stripped-down picker, then hands the
/// actual prepare+upload off to [UploadService] - a real Android foreground
/// service (see `ShareUploadService.kt`'s doc comment), not something this
/// screen or even the app needs to stay open for. [files] only ever carry
/// cheap Uri metadata (see [ShareIntentService]'s doc comment); that
/// service is the only thing that ever reads their actual bytes.
class ShareUploadView extends StatefulWidget {
final List<SharedMediaFile> files;
final List<SharedFileRef> files;
const ShareUploadView({super.key, required this.files});
@@ -20,10 +32,6 @@ class ShareUploadView extends StatefulWidget {
}
class _ShareUploadViewState extends State<ShareUploadView> {
bool _uploading = false;
int _currentFileIndex = 0;
double? _currentFileProgress;
@override
void initState() {
super.initState();
@@ -35,46 +43,283 @@ class _ShareUploadViewState extends State<ShareUploadView> {
}
Future<void> _uploadHere(ServerProvider provider) async {
setState(() => _uploading = true);
var anyFailed = false;
for (var i = 0; i < widget.files.length; i++) {
final file = widget.files[i];
setState(() {
_currentFileIndex = i;
_currentFileProgress = 0;
});
final name = p.basename(file.path);
final success = await provider.uploadFileFromPath(
name,
file.path,
onProgress: (sent, total) {
if (total > 0 && mounted) {
setState(() => _currentFileProgress = sent / total);
}
},
final messenger = ScaffoldMessenger.of(context);
final navigator = Navigator.of(context);
try {
await UploadService.startUpload(provider, widget.files);
} catch (e) {
messenger.showSnackBar(
SnackBar(
content: Text('Could not start upload: $e'),
behavior: SnackBarBehavior.floating,
),
);
if (!success) anyFailed = true;
return;
}
if (!mounted) return;
provider.requestTab(AppTab.files);
Navigator.of(context).popUntil((route) => route.isFirst);
ScaffoldMessenger.of(context).showSnackBar(
navigator.popUntil((route) => route.isFirst);
messenger.showSnackBar(
SnackBar(
content: Text(
anyFailed
? 'Some files failed to upload'
: widget.files.length == 1
? 'Uploaded ${p.basename(widget.files.first.path)}'
: 'Uploaded ${widget.files.length} files',
widget.files.length == 1
? 'Uploading ${widget.files.first.name} - see the notification for progress'
: 'Uploading ${widget.files.length} files - see the notification for progress',
),
behavior: SnackBarBehavior.floating,
),
);
}
Widget _buildControlsRow(ServerProvider provider) {
return SizedBox(
height: 44,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
IconButton(
icon: Icon(
provider.filesSortAscending
? Icons.arrow_upward_rounded
: Icons.arrow_downward_rounded,
size: 20,
),
visualDensity: VisualDensity.compact,
tooltip: provider.filesSortAscending ? 'Ascending' : 'Descending',
onPressed: provider.toggleFilesSortOrder,
),
SizedBox(
width: 130,
child: SortMenuButton(
field: provider.filesSortField,
onChanged: provider.setFilesSortField,
),
),
ToggleIconButton(
icon: provider.showFavoritesOnlyFiles
? Icons.favorite_rounded
: Icons.favorite_border_rounded,
isSelected: provider.showFavoritesOnlyFiles,
onTap: provider.toggleFavoritesFilterFiles,
tooltip: 'Favorites only',
),
const SizedBox(width: 4),
ToggleIconButton(
icon: provider.showHiddenFiles
? Icons.visibility_rounded
: Icons.visibility_off_rounded,
isSelected: provider.showHiddenFiles,
onTap: () => provider.toggleShowHiddenFiles(),
tooltip: 'Show hidden files',
),
const SizedBox(width: 4),
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Symbols.circles_rounded,
isSelected: provider.storageScope == StorageScope.cloud,
onTap: () => provider.setStorageScope(StorageScope.cloud),
tooltip: 'Cloud storage',
),
ToggleIconButton(
icon: Symbols.hard_drive_rounded,
isSelected: provider.storageScope == StorageScope.external,
onTap: () => provider.setStorageScope(StorageScope.external),
tooltip: 'External storage',
),
],
),
const SizedBox(width: 8),
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Icons.select_all_rounded,
isSelected: provider.filesTypeFilter == FilesTypeFilter.all,
onTap: () => provider.setFilesTypeFilter(FilesTypeFilter.all),
tooltip: 'Files & folders',
),
ToggleIconButton(
icon: Icons.insert_drive_file_outlined,
isSelected:
provider.filesTypeFilter == FilesTypeFilter.filesOnly,
onTap: () =>
provider.setFilesTypeFilter(FilesTypeFilter.filesOnly),
tooltip: 'Files only',
),
ToggleIconButton(
icon: Icons.folder_outlined,
isSelected:
provider.filesTypeFilter == FilesTypeFilter.foldersOnly,
onTap: () =>
provider.setFilesTypeFilter(FilesTypeFilter.foldersOnly),
tooltip: 'Folders only',
),
],
),
const SizedBox(width: 8),
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Icons.view_list_rounded,
isSelected: !provider.isGridView,
onTap: () => provider.setGridView(false),
tooltip: 'List view',
),
ToggleIconButton(
icon: Icons.grid_view_rounded,
isSelected: provider.isGridView,
onTap: () => provider.setGridView(true),
tooltip: 'Grid view',
),
],
),
],
),
),
);
}
// Only folders are valid upload destinations - files still show (so the
// listing matches what the Files tab itself would show for this folder)
// but are visually dimmed and inert rather than hidden outright.
Widget _buildListTile(
BuildContext context,
NextcloudItem item,
ServerProvider provider,
) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final isFolder = item.isFolder;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Opacity(
opacity: isFolder ? 1 : 0.5,
child: Material(
color: colorScheme.surfaceContainerLow,
child: InkWell(
onTap: isFolder
? () => provider.navigateToFolder(item.path)
: null,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
child: Row(
children: [
ItemThumbnail(
item: item,
provider: provider,
size: 44,
borderRadius: 12,
iconSize: 22,
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
const SizedBox(height: 2),
Text(
isFolder
? 'Folder'
: '${formatBytes(item.size)} • ${DateFormat.yMMMd().format(item.lastModified)}',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
if (isFolder) const Icon(Icons.chevron_right_rounded),
],
),
),
),
),
),
),
);
}
Widget _buildGridCard(
BuildContext context,
NextcloudItem item,
ServerProvider provider,
) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final isFolder = item.isFolder;
final iconColor = getIconColor(context, item.type);
return Opacity(
opacity: isFolder ? 1 : 0.5,
child: Material(
color: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(20),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: isFolder ? () => provider.navigateToFolder(item.path) : null,
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: iconColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12),
),
child: Icon(
getItemIcon(item.type),
color: iconColor,
size: 24,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
fontSize: 13,
),
),
const SizedBox(height: 2),
Text(
isFolder ? 'Folder' : formatBytes(item.size),
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
],
),
),
),
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
@@ -85,94 +330,79 @@ class _ShareUploadViewState extends State<ShareUploadView> {
final currentLabel = currentPath == '/'
? 'Home'
: currentPath.split('/').where((s) => s.isNotEmpty).last;
final folders = provider.items.where((i) => i.isFolder).toList();
final items = provider.items;
return Scaffold(
appBar: AppBar(
title: Text(
widget.files.length == 1
? 'Upload ${p.basename(widget.files.first.path)}'
? 'Upload ${widget.files.first.name}'
: 'Upload ${widget.files.length} files',
),
),
body: _uploading
? Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(
value: _currentFileProgress,
color: colorScheme.primary,
),
const SizedBox(height: 20),
Text(
widget.files.length == 1
? 'Uploading ${p.basename(widget.files[_currentFileIndex].path)}…'
: 'Uploading ${_currentFileIndex + 1} of ${widget.files.length}…',
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: _buildControlsRow(provider),
),
if (hasBreadcrumbs)
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
child: Breadcrumbs(
pathStack: provider.pathStack,
onTap: (index) => provider.navigateToPathIndex(index),
),
)
: Column(
children: [
if (hasBreadcrumbs)
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: Breadcrumbs(
pathStack: provider.pathStack,
onTap: (index) => provider.navigateToPathIndex(index),
),
Expanded(
child: provider.isLoading
? const Center(child: CircularProgressIndicator())
: items.isEmpty
? Center(
child: Text(
'Folder is empty',
style: TextStyle(color: colorScheme.onSurfaceVariant),
),
),
Expanded(
child: provider.isLoading
? const Center(child: CircularProgressIndicator())
: folders.isEmpty
? Center(
child: Text(
'No subfolders here',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
),
),
)
: ListView.builder(
itemCount: folders.length,
itemBuilder: (context, index) {
final folder = folders[index];
return ListTile(
leading: Icon(
Icons.folder_rounded,
color: colorScheme.primary,
),
title: Text(folder.name),
trailing: const Icon(Icons.chevron_right_rounded),
onTap: () =>
provider.navigateToFolder(folder.path),
);
},
)
: provider.isGridView
? GridView.builder(
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 8,
),
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 1.1,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
),
],
),
bottomNavigationBar: _uploading
? null
: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: FilledButton.icon(
onPressed: () => _uploadHere(provider),
icon: const Icon(Icons.upload_rounded),
label: Text('Upload to $currentLabel'),
),
),
),
itemCount: items.length,
itemBuilder: (context, index) =>
_buildGridCard(context, items[index], provider),
)
: ListView.builder(
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 8,
),
itemCount: items.length,
itemBuilder: (context, index) =>
_buildListTile(context, items[index], provider),
),
),
],
),
bottomNavigationBar: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: FilledButton.icon(
onPressed: () => _uploadHere(provider),
icon: const Icon(Icons.upload_rounded),
label: Text('Upload to $currentLabel'),
),
),
),
);
}
}