Initial commit

Flutter Nextcloud client app.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-15 11:54:26 -04:00
co-authored by Claude Sonnet 5
commit 54f80a65e7
102 changed files with 6271 additions and 0 deletions
+138
View File
@@ -0,0 +1,138 @@
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:provider/provider.dart';
import 'providers/server_provider.dart';
import 'theme/app_theme.dart';
import 'views/account_view.dart';
import 'views/activity_view.dart';
import 'views/files_view.dart';
import 'views/login_view.dart';
import 'views/photos_view.dart';
import 'widgets/floating_bottom_bar.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(
ChangeNotifierProvider(
create: (_) => ServerProvider(),
child: const NextcloudApp(),
),
);
}
class NextcloudApp extends StatelessWidget {
const NextcloudApp({super.key});
@override
Widget build(BuildContext context) {
final provider = context.watch<ServerProvider>();
return MaterialApp(
title: 'Nextcloud Material',
debugShowCheckedModeBanner: false,
theme: AppTheme.light(provider.seedColor),
darkTheme: AppTheme.dark(provider.seedColor),
themeMode: provider.themeMode,
home: provider.isLoggedIn ? const MainShellView() : const LoginView(),
);
}
}
class MainShellView extends StatefulWidget {
const MainShellView({super.key});
@override
State<MainShellView> createState() => _MainShellViewState();
}
class _MainShellViewState extends State<MainShellView> {
int _currentIndex = 0;
bool _isNavVisible = true;
late final List<ScrollController> _scrollControllers;
@override
void initState() {
super.initState();
_scrollControllers = List.generate(4, (index) {
final controller = ScrollController();
controller.addListener(() {
if (controller.position.userScrollDirection == ScrollDirection.reverse) {
if (_isNavVisible) {
setState(() {
_isNavVisible = false;
});
}
} else if (controller.position.userScrollDirection == ScrollDirection.forward) {
if (!_isNavVisible) {
setState(() {
_isNavVisible = true;
});
}
}
});
return controller;
});
}
@override
void dispose() {
for (var c in _scrollControllers) {
c.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
final navItems = const [
FloatingNavItem(
label: 'Files',
icon: Icons.folder_outlined,
selectedIcon: Icons.folder_rounded,
),
FloatingNavItem(
label: 'Photos',
icon: Icons.photo_library_outlined,
selectedIcon: Icons.photo_library_rounded,
),
FloatingNavItem(
label: 'Activity',
icon: Icons.history_rounded,
selectedIcon: Icons.history_toggle_off_rounded,
),
FloatingNavItem(
label: 'Account',
icon: Icons.account_circle_outlined,
selectedIcon: Icons.account_circle_rounded,
),
];
return Scaffold(
body: Stack(
children: [
IndexedStack(
index: _currentIndex,
children: [
FilesView(scrollController: _scrollControllers[0]),
PhotosView(scrollController: _scrollControllers[1]),
ActivityView(scrollController: _scrollControllers[2]),
AccountView(scrollController: _scrollControllers[3]),
],
),
FloatingBottomNavBar(
selectedIndex: _currentIndex,
items: navItems,
isVisible: _isNavVisible,
onDestinationSelected: (index) {
setState(() {
_currentIndex = index;
_isNavVisible = true;
});
},
),
],
),
);
}
}
+134
View File
@@ -0,0 +1,134 @@
import 'package:flutter/material.dart';
enum NextcloudItemType { file, folder, image, video, document, audio, archive }
class NextcloudItem {
final String id;
final String name;
final String path;
final NextcloudItemType type;
final int size; // in bytes
final DateTime lastModified;
final bool isFavorite;
final String? mimeType;
final String? etag;
final String? previewUrl;
final int? imageWidth;
final int? imageHeight;
const NextcloudItem({
required this.id,
required this.name,
required this.path,
required this.type,
required this.size,
required this.lastModified,
this.isFavorite = false,
this.mimeType,
this.etag,
this.previewUrl,
this.imageWidth,
this.imageHeight,
});
bool get isFolder => type == NextcloudItemType.folder;
bool get isMedia => type == NextcloudItemType.image || type == NextcloudItemType.video;
NextcloudItem copyWith({
String? id,
String? name,
String? path,
NextcloudItemType? type,
int? size,
DateTime? lastModified,
bool? isFavorite,
String? mimeType,
String? etag,
String? previewUrl,
int? imageWidth,
int? imageHeight,
}) {
return NextcloudItem(
id: id ?? this.id,
name: name ?? this.name,
path: path ?? this.path,
type: type ?? this.type,
size: size ?? this.size,
lastModified: lastModified ?? this.lastModified,
isFavorite: isFavorite ?? this.isFavorite,
mimeType: mimeType ?? this.mimeType,
etag: etag ?? this.etag,
previewUrl: previewUrl ?? this.previewUrl,
imageWidth: imageWidth ?? this.imageWidth,
imageHeight: imageHeight ?? this.imageHeight,
);
}
static NextcloudItemType deduceType(String path, bool isCollection, String? mime) {
if (isCollection) return NextcloudItemType.folder;
final lower = path.toLowerCase();
if (mime?.startsWith('image/') == true || lower.endsWith('.jpg') || lower.endsWith('.jpeg') || lower.endsWith('.png') || lower.endsWith('.webp') || lower.endsWith('.gif') || lower.endsWith('.heic')) {
return NextcloudItemType.image;
}
if (mime?.startsWith('video/') == true || lower.endsWith('.mp4') || lower.endsWith('.mov') || lower.endsWith('.mkv') || lower.endsWith('.webm')) {
return NextcloudItemType.video;
}
if (mime?.startsWith('audio/') == true || lower.endsWith('.mp3') || lower.endsWith('.flac') || lower.endsWith('.wav') || lower.endsWith('.ogg')) {
return NextcloudItemType.audio;
}
if (lower.endsWith('.pdf') || lower.endsWith('.txt') || lower.endsWith('.md') || lower.endsWith('.docx') || lower.endsWith('.xlsx')) {
return NextcloudItemType.document;
}
if (lower.endsWith('.zip') || lower.endsWith('.tar') || lower.endsWith('.gz') || lower.endsWith('.7z')) {
return NextcloudItemType.archive;
}
return NextcloudItemType.file;
}
}
class NextcloudUserQuota {
final int usedBytes;
final int totalBytes;
final double usagePercentage;
final String userName;
final String email;
final String serverVersion;
const NextcloudUserQuota({
required this.usedBytes,
required this.totalBytes,
required this.usagePercentage,
required this.userName,
required this.email,
required this.serverVersion,
});
factory NextcloudUserQuota.demo() {
return const NextcloudUserQuota(
usedBytes: 48500000000, // ~45.17 GB
totalBytes: 107374182400, // 100 GB
usagePercentage: 0.4517,
userName: 'Ayush Admin',
email: 'ayush@cloud.internal',
serverVersion: 'Nextcloud 29.0.4 Hub 8',
);
}
}
class NextcloudActivity {
final String id;
final String title;
final String subject;
final DateTime timestamp;
final IconData icon;
final String author;
const NextcloudActivity({
required this.id,
required this.title,
required this.subject,
required this.timestamp,
required this.icon,
required this.author,
});
}
+290
View File
@@ -0,0 +1,290 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../models/nextcloud_item.dart';
import '../services/nextcloud_service.dart';
import '../theme/app_theme.dart';
class ServerProvider extends ChangeNotifier {
String _serverUrl = '';
String _username = '';
String _password = '';
bool _isLoggedIn = false;
bool _isLoading = false;
String? _errorMessage;
// Theme state
Color _seedColor = AppTheme.defaultNextcloudBlue;
ThemeMode _themeMode = ThemeMode.system;
// Navigation state
String _currentFolderPath = '/';
List<String> _pathStack = ['/'];
bool _isGridView = false;
String _searchQuery = '';
bool _showFavoritesOnly = false;
// Data state
List<NextcloudItem> _items = [];
NextcloudUserQuota? _quota;
List<NextcloudActivity> _activities = [];
NextcloudService? _service;
ServerProvider() {
_loadSavedSession();
}
// Getters
String get serverUrl => _serverUrl;
String get username => _username;
String get password => _password;
bool get isLoggedIn => _isLoggedIn;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
Color get seedColor => _seedColor;
ThemeMode get themeMode => _themeMode;
String get currentFolderPath => _currentFolderPath;
List<String> get pathStack => _pathStack;
bool get isGridView => _isGridView;
String get searchQuery => _searchQuery;
bool get showFavoritesOnly => _showFavoritesOnly;
List<NextcloudItem> get items {
var filtered = _items;
if (_showFavoritesOnly) {
filtered = filtered.where((item) => item.isFavorite).toList();
}
if (_searchQuery.trim().isNotEmpty) {
final query = _searchQuery.toLowerCase();
filtered = filtered.where((item) => item.name.toLowerCase().contains(query)).toList();
}
return filtered;
}
List<NextcloudItem> get photoItems {
final allMedia = _items.where((i) => i.isMedia || i.type == NextcloudItemType.image).toList();
if (_searchQuery.trim().isNotEmpty) {
final query = _searchQuery.toLowerCase();
return allMedia.where((i) => i.name.toLowerCase().contains(query)).toList();
}
return allMedia;
}
NextcloudUserQuota? get quota => _quota;
List<NextcloudActivity> get activities => _activities;
Future<void> _loadSavedSession() async {
try {
final file = File('.nextcloud_session.json');
if (await file.exists()) {
final content = await file.readAsString();
final data = jsonDecode(content);
if (data['serverUrl'] != null && data['username'] != null && data['password'] != null) {
final sUrl = data['serverUrl'].toString();
final uName = data['username'].toString();
final pWord = data['password'].toString();
if (sUrl.isNotEmpty && uName.isNotEmpty && pWord.isNotEmpty) {
await login(serverUrl: sUrl, username: uName, password: pWord, saveSession: false);
}
}
}
} catch (_) {}
}
Future<void> _saveSession() async {
try {
final file = File('.nextcloud_session.json');
final data = {
'serverUrl': _serverUrl,
'username': _username,
'password': _password,
};
await file.writeAsString(jsonEncode(data));
} catch (_) {}
}
Future<void> _clearSavedSession() async {
try {
final file = File('.nextcloud_session.json');
if (await file.exists()) {
await file.delete();
}
} catch (_) {}
}
Future<bool> login({
required String serverUrl,
required String username,
required String password,
bool saveSession = true,
}) async {
_isLoading = true;
_errorMessage = null;
notifyListeners();
_serverUrl = serverUrl;
_username = username;
_password = password;
_service = NextcloudService(
serverUrl: _serverUrl,
username: _username,
password: _password,
);
try {
final success = await _service!.testConnection();
if (success) {
_isLoggedIn = true;
_currentFolderPath = '/';
_pathStack = ['/'];
if (saveSession) {
await _saveSession();
}
await refreshData();
_isLoading = false;
notifyListeners();
return true;
}
} catch (e) {
_errorMessage = e.toString().replaceAll('Exception: ', '');
}
_isLoggedIn = false;
_isLoading = false;
notifyListeners();
return false;
}
Future<void> logout() async {
_isLoggedIn = false;
_serverUrl = '';
_username = '';
_password = '';
_items = [];
_quota = null;
_activities = [];
_service = null;
await _clearSavedSession();
notifyListeners();
}
Future<void> refreshData() async {
if (!_isLoggedIn || _service == null) {
debugPrint('[ServerProvider] refreshData skipped: isLoggedIn=$_isLoggedIn, service=${_service != null}');
return;
}
_isLoading = true;
_errorMessage = null;
notifyListeners();
debugPrint('[ServerProvider] Refreshing data for path: $_currentFolderPath');
try {
_items = await _service!.fetchDirectory(_currentFolderPath);
debugPrint('[ServerProvider] Loaded ${_items.length} items for $_currentFolderPath');
try {
_quota = await _service!.fetchUserQuota();
debugPrint('[ServerProvider] Loaded quota: used=${_quota?.usedBytes}, total=${_quota?.totalBytes}');
} catch (e) {
debugPrint('[ServerProvider] Quota fetch warning: $e');
}
try {
_activities = await _service!.fetchActivities();
debugPrint('[ServerProvider] Loaded ${_activities.length} activity items');
} catch (e) {
debugPrint('[ServerProvider] Activity fetch warning: $e');
}
} catch (e) {
debugPrint('[ServerProvider] Error fetching directory: $e');
_errorMessage = e.toString().replaceAll('Exception: ', '');
} finally {
_isLoading = false;
notifyListeners();
}
}
Future<void> navigateToFolder(String path) async {
_currentFolderPath = path;
_pathStack.add(path);
await refreshData();
}
Future<void> navigateUp() async {
if (_pathStack.length > 1) {
_pathStack.removeLast();
_currentFolderPath = _pathStack.last;
await refreshData();
}
}
void toggleViewMode() {
_isGridView = !_isGridView;
notifyListeners();
}
void setSearchQuery(String query) {
_searchQuery = query;
notifyListeners();
}
void toggleFavoritesFilter() {
_showFavoritesOnly = !_showFavoritesOnly;
notifyListeners();
}
Future<bool> uploadFile(String name, Uint8List bytes) async {
if (_service == null) return false;
final success = await _service!.uploadFile(_currentFolderPath, name, bytes);
if (success) {
await refreshData();
}
return success;
}
Future<bool> deleteItem(String itemPath) async {
if (_service == null) return false;
final success = await _service!.deleteItem(itemPath);
if (success) {
await refreshData();
}
return success;
}
Future<bool> createFolder(String folderName) async {
if (_service == null) return false;
final success = await _service!.createFolder(_currentFolderPath, folderName);
if (success) {
await refreshData();
}
return success;
}
Future<void> toggleItemFavorite(NextcloudItem item) async {
if (_service == null) return;
final success = await _service!.toggleFavorite(item.path, item.isFavorite);
if (success) {
final index = _items.indexWhere((i) => i.id == item.id);
if (index != -1) {
_items[index] = item.copyWith(isFavorite: !item.isFavorite);
notifyListeners();
}
}
}
void setSeedColor(Color color) {
_seedColor = color;
notifyListeners();
}
void setThemeMode(ThemeMode mode) {
_themeMode = mode;
notifyListeners();
}
}
+403
View File
@@ -0,0 +1,403 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:xml/xml.dart' as xml;
import '../models/nextcloud_item.dart';
extension XmlElementHelper on xml.XmlNode {
Iterable<xml.XmlElement> findLocalChildren(String localName) {
return children.whereType<xml.XmlElement>().where(
(e) => e.name.local.toLowerCase() == localName.toLowerCase(),
);
}
Iterable<xml.XmlElement> findLocalDescendants(String localName) {
if (this is xml.XmlDocument) {
return (this as xml.XmlDocument).descendants.whereType<xml.XmlElement>().where(
(e) => e.name.local.toLowerCase() == localName.toLowerCase(),
);
} else if (this is xml.XmlElement) {
return (this as xml.XmlElement).descendants.whereType<xml.XmlElement>().where(
(e) => e.name.local.toLowerCase() == localName.toLowerCase(),
);
}
return [];
}
}
class NextcloudService {
final String serverUrl;
final String username;
final String password;
NextcloudService({
required this.serverUrl,
required this.username,
required this.password,
});
String get _cleanServerUrl {
var url = serverUrl.trim();
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://$url';
}
if (url.endsWith('/')) {
url = url.substring(0, url.length - 1);
}
return url;
}
Map<String, String> get _headers {
final credentials = base64Encode(utf8.encode('$username:$password'));
return {
'Authorization': 'Basic $credentials',
'OCS-APIRequest': 'true',
'Accept': 'application/json, application/xml',
'User-Agent': 'Nextcloud-Flutter-Client/1.0',
};
}
Future<bool> testConnection() async {
try {
final davPath = '$_cleanServerUrl/remote.php/dav/files/$username/';
debugPrint('[Nextcloud Test] Connecting to WebDAV endpoint: $davPath');
final request = http.Request('PROPFIND', Uri.parse(davPath))
..headers.addAll({
..._headers,
'Depth': '0',
'Content-Type': 'application/xml',
})
..body = '''<?xml version="1.0" encoding="utf-8" ?>
<d:propfind xmlns:d="DAV:">
<d:prop>
<d:resourcetype/>
</d:prop>
</d:propfind>''';
final streamed = await http.Client().send(request);
debugPrint('[Nextcloud Test] Connection response HTTP status: ${streamed.statusCode}');
if (streamed.statusCode == 207 || streamed.statusCode == 200) {
return true;
}
// Try fallback endpoint /remote.php/webdav/
final legacyPath = '$_cleanServerUrl/remote.php/webdav/';
debugPrint('[Nextcloud Test] Testing legacy WebDAV endpoint: $legacyPath');
final req2 = http.Request('PROPFIND', Uri.parse(legacyPath))
..headers.addAll({
..._headers,
'Depth': '0',
'Content-Type': 'application/xml',
});
final st2 = await http.Client().send(req2);
debugPrint('[Nextcloud Test] Legacy WebDAV response HTTP status: ${st2.statusCode}');
if (st2.statusCode == 207 || st2.statusCode == 200) {
return true;
}
if (streamed.statusCode == 401 || st2.statusCode == 401) {
throw Exception('Invalid username or password (401 Unauthorized)');
} else if (streamed.statusCode == 404 && st2.statusCode == 404) {
throw Exception('Nextcloud WebDAV endpoint not found at $davPath');
} else {
throw Exception('Server returned status code ${streamed.statusCode}');
}
} catch (e) {
debugPrint('[Nextcloud Test] Error: $e');
final str = e.toString();
if (str.contains('XMLHttpRequest') || str.contains('ClientException') || str.contains('Failed to fetch')) {
throw Exception(
'Browser CORS Policy Blocked: The web browser blocked the connection preflight request to $_cleanServerUrl. '
'To bypass browser CORS, run the application as a native Windows app (flutter run -d windows) '
'or configure CORS headers on your Nextcloud server.',
);
}
if (e is Exception) rethrow;
throw Exception('Could not connect to Nextcloud host: $e');
}
}
Future<List<NextcloudItem>> fetchDirectory(String folderPath) async {
var cleanPath = folderPath.trim();
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
if (!cleanPath.endsWith('/')) cleanPath = '$cleanPath/';
final url = '$_cleanServerUrl/remote.php/dav/files/$username$cleanPath';
debugPrint('[Nextcloud DAV] Requesting PROPFIND for $url');
final request = http.Request('PROPFIND', Uri.parse(url))
..headers.addAll({
..._headers,
'Depth': '1',
'Content-Type': 'application/xml',
});
const body = '''<?xml version="1.0" encoding="utf-8" ?>
<d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
<d:prop>
<d:getlastmodified/>
<d:getcontentlength/>
<d:getcontenttype/>
<d:resourcetype/>
<oc:favorite/>
<oc:fileid/>
<oc:size/>
</d:prop>
</d:propfind>''';
request.body = body;
var streamedResponse = await http.Client().send(request);
var responseBody = await streamedResponse.stream.bytesToString();
debugPrint('[Nextcloud DAV] PROPFIND primary URL status: ${streamedResponse.statusCode}, bytes: ${responseBody.length}');
if (streamedResponse.statusCode != 207 && streamedResponse.statusCode != 200) {
final fallbackUrl = '$_cleanServerUrl/remote.php/webdav$cleanPath';
debugPrint('[Nextcloud DAV] Primary URL failed (${streamedResponse.statusCode}). Trying fallback: $fallbackUrl');
final req2 = http.Request('PROPFIND', Uri.parse(fallbackUrl))
..headers.addAll({
..._headers,
'Depth': '1',
'Content-Type': 'application/xml',
})
..body = body;
final res2 = await http.Client().send(req2);
final body2 = await res2.stream.bytesToString();
debugPrint('[Nextcloud DAV] Fallback URL response status: ${res2.statusCode}, bytes: ${body2.length}');
if (res2.statusCode == 207 || res2.statusCode == 200) {
streamedResponse = res2;
responseBody = body2;
} else {
throw Exception('Failed to load directory $cleanPath. HTTP ${streamedResponse.statusCode}');
}
}
final document = xml.XmlDocument.parse(responseBody);
final responses = document.findLocalDescendants('response');
debugPrint('[Nextcloud DAV] Found ${responses.length} response nodes in XML');
List<NextcloudItem> items = [];
for (var res in responses) {
final hrefNode = res.findLocalChildren('href').firstOrNull ?? res.findLocalDescendants('href').firstOrNull;
final href = hrefNode?.innerText ?? '';
var normalizedHref = Uri.decodeFull(href).trim();
if (normalizedHref.endsWith('/') && normalizedHref.length > 1) {
normalizedHref = normalizedHref.substring(0, normalizedHref.length - 1);
}
var targetDav = '$_cleanServerUrl/remote.php/dav/files/$username$cleanPath'.trim();
if (targetDav.endsWith('/') && targetDav.length > 1) {
targetDav = targetDav.substring(0, targetDav.length - 1);
}
var targetLegacy = '$_cleanServerUrl/remote.php/webdav$cleanPath'.trim();
if (targetLegacy.endsWith('/') && targetLegacy.length > 1) {
targetLegacy = targetLegacy.substring(0, targetLegacy.length - 1);
}
// Skip current root directory entry itself
if (normalizedHref == targetDav ||
normalizedHref == targetLegacy ||
normalizedHref.endsWith('/remote.php/dav/files/$username') ||
normalizedHref.endsWith('/remote.php/webdav')) {
continue;
}
final props = res.findLocalDescendants('prop');
if (props.isEmpty) continue;
bool isCollection = false;
String? sizeStr;
String? lastModStr;
String? mimeType;
bool isFav = false;
String? fileId;
for (var prop in props) {
if (!isCollection) {
final resTypeNode = prop.findLocalChildren('resourcetype').firstOrNull;
if (resTypeNode != null && resTypeNode.findLocalChildren('collection').isNotEmpty) {
isCollection = true;
}
}
sizeStr ??= prop.findLocalChildren('size').firstOrNull?.innerText ??
prop.findLocalChildren('getcontentlength').firstOrNull?.innerText;
lastModStr ??= prop.findLocalChildren('getlastmodified').firstOrNull?.innerText;
mimeType ??= prop.findLocalChildren('getcontenttype').firstOrNull?.innerText;
if (!isFav) {
isFav = prop.findLocalChildren('favorite').firstOrNull?.innerText == '1';
}
fileId ??= prop.findLocalChildren('fileid').firstOrNull?.innerText;
}
final name = Uri.decodeFull(href.split('/').where((s) => s.isNotEmpty).last);
if (name.isEmpty) continue;
final size = int.tryParse(sizeStr ?? '0') ?? 0;
final lastMod = lastModStr != null ? DateTime.tryParse(lastModStr) ?? DateTime.now() : DateTime.now();
final itemType = NextcloudItem.deduceType(name, isCollection, mimeType);
final validId = (fileId != null && fileId.isNotEmpty) ? fileId : name;
items.add(NextcloudItem(
id: validId,
name: name,
path: '$cleanPath$name',
type: itemType,
size: size,
lastModified: lastMod,
isFavorite: isFav,
mimeType: mimeType,
previewUrl: '$_cleanServerUrl/core/preview?fileId=$validId&x=500&y=500',
));
}
debugPrint('[Nextcloud DAV] Successfully parsed ${items.length} items from directory $cleanPath');
return items;
}
Future<NextcloudUserQuota> fetchUserQuota() async {
final url = '$_cleanServerUrl/ocs/v1.php/cloud/user?format=json';
debugPrint('[Nextcloud OCS] Fetching user quota from $url');
final response = await http.get(Uri.parse(url), headers: _headers);
debugPrint('[Nextcloud OCS] User quota response status: ${response.statusCode}');
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final ocsData = data['ocs']?['data'] ?? {};
final quota = ocsData['quota'] ?? {};
final used = (quota['used'] as num?)?.toInt() ?? 0;
final totalRaw = (quota['total'] as num?)?.toInt() ?? 0;
final total = totalRaw < 0 ? -1 : totalRaw;
final pct = total > 0 ? (used / total).clamp(0.0, 1.0) : 0.0;
final display = ocsData['displayname'] ?? username;
final email = ocsData['email'] ?? '$username@$serverUrl';
return NextcloudUserQuota(
usedBytes: used,
totalBytes: total,
usagePercentage: pct,
userName: display,
email: email,
serverVersion: 'Nextcloud Server',
);
} else {
throw Exception('Failed to fetch user quota. HTTP ${response.statusCode}');
}
}
Future<List<NextcloudActivity>> fetchActivities() async {
try {
final url = '$_cleanServerUrl/ocs/v2.php/apps/activity/api/v2/activity?format=json';
debugPrint('[Nextcloud OCS] Fetching activity feed from $url');
final response = await http.get(Uri.parse(url), headers: _headers);
debugPrint('[Nextcloud OCS] Activity response status: ${response.statusCode}');
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final rawData = data['ocs']?['data'];
List<dynamic> list = [];
if (rawData is List) {
list = rawData;
} else if (rawData is Map && rawData['activity'] is List) {
list = rawData['activity'];
}
return list.map((a) {
return NextcloudActivity(
id: (a['activity_id'] ?? '').toString(),
title: a['subject'] ?? 'Server Activity',
subject: a['message'] ?? (a['subject'] ?? ''),
timestamp: DateTime.fromMillisecondsSinceEpoch((a['timestamp'] as int? ?? 0) * 1000),
icon: Icons.cloud_outlined,
author: a['user'] ?? username,
);
}).toList();
}
} catch (e) {
debugPrint('[Nextcloud OCS Activity] Error: $e');
}
return [];
}
Future<bool> uploadFile(String folderPath, String fileName, Uint8List fileBytes) async {
var cleanPath = folderPath.trim();
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
if (!cleanPath.endsWith('/')) cleanPath = '$cleanPath/';
final url = '$_cleanServerUrl/remote.php/dav/files/$username$cleanPath$fileName';
debugPrint('[Nextcloud DAV] Uploading file to $url');
final response = await http.put(
Uri.parse(url),
headers: {
..._headers,
'Content-Type': 'application/octet-stream',
},
body: fileBytes,
);
debugPrint('[Nextcloud DAV] Upload status: ${response.statusCode}');
return response.statusCode == 201 || response.statusCode == 204 || response.statusCode == 200;
}
Future<bool> deleteItem(String itemPath) async {
var cleanPath = itemPath.trim();
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
final url = '$_cleanServerUrl/remote.php/dav/files/$username$cleanPath';
debugPrint('[Nextcloud DAV] Deleting item at $url');
final response = await http.delete(Uri.parse(url), headers: _headers);
debugPrint('[Nextcloud DAV] Delete status: ${response.statusCode}');
return response.statusCode == 204 || response.statusCode == 200;
}
Future<bool> createFolder(String parentPath, String folderName) async {
var cleanPath = parentPath.trim();
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
if (!cleanPath.endsWith('/')) cleanPath = '$cleanPath/';
final url = '$_cleanServerUrl/remote.php/dav/files/$username$cleanPath$folderName';
debugPrint('[Nextcloud DAV] Creating folder at $url');
final request = http.Request('MKCOL', Uri.parse(url))..headers.addAll(_headers);
final response = await http.Client().send(request);
debugPrint('[Nextcloud DAV] Create folder status: ${response.statusCode}');
return response.statusCode == 201;
}
Future<bool> toggleFavorite(String itemPath, bool currentFavoriteState) async {
var cleanPath = itemPath.trim();
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
final url = '$_cleanServerUrl/remote.php/dav/files/$username$cleanPath';
final newFavVal = currentFavoriteState ? '0' : '1';
debugPrint('[Nextcloud DAV] Toggling favorite ($newFavVal) for $url');
final body = '''<?xml version="1.0" encoding="utf-8" ?>
<d:propertyupdate xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
<d:set>
<d:prop>
<oc:favorite>$newFavVal</oc:favorite>
</d:prop>
</d:set>
</d:propertyupdate>''';
final request = http.Request('PROPPATCH', Uri.parse(url))
..headers.addAll({
..._headers,
'Content-Type': 'application/xml',
})
..body = body;
final response = await http.Client().send(request);
debugPrint('[Nextcloud DAV] Toggle favorite status: ${response.statusCode}');
return response.statusCode == 207 || response.statusCode == 200;
}
}
+104
View File
@@ -0,0 +1,104 @@
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class AppTheme {
static const Color defaultNextcloudBlue = Color(0xFF0082C9);
static const List<Color> seedColors = [
Color(0xFF0082C9), // Nextcloud Blue
Color(0xFF009688), // Ocean Teal
Color(0xFF6750A4), // Deep Purple
Color(0xFFE65100), // Sunset Amber
Color(0xFF2E7D32), // Emerald Green
];
static ThemeData light(Color seedColor) {
final colorScheme = ColorScheme.fromSeed(
seedColor: seedColor,
brightness: Brightness.light,
);
return ThemeData(
useMaterial3: true,
brightness: Brightness.light,
colorScheme: colorScheme,
scaffoldBackgroundColor: colorScheme.surface,
textTheme: GoogleFonts.interTextTheme(ThemeData.light().textTheme).copyWith(
headlineMedium: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.5,
),
titleLarge: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.2,
),
titleMedium: GoogleFonts.inter(
fontWeight: FontWeight.w500,
),
),
cardTheme: CardThemeData(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
color: colorScheme.surfaceContainerLow,
),
appBarTheme: AppBarTheme(
backgroundColor: colorScheme.surface,
elevation: 0,
scrolledUnderElevation: 0,
centerTitle: false,
titleTextStyle: GoogleFonts.inter(
fontSize: 22,
fontWeight: FontWeight.w600,
color: colorScheme.onSurface,
),
),
);
}
static ThemeData dark(Color seedColor) {
final colorScheme = ColorScheme.fromSeed(
seedColor: seedColor,
brightness: Brightness.dark,
);
return ThemeData(
useMaterial3: true,
brightness: Brightness.dark,
colorScheme: colorScheme,
scaffoldBackgroundColor: colorScheme.surface,
textTheme: GoogleFonts.interTextTheme(ThemeData.dark().textTheme).copyWith(
headlineMedium: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.5,
),
titleLarge: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.2,
),
titleMedium: GoogleFonts.inter(
fontWeight: FontWeight.w500,
),
),
cardTheme: CardThemeData(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
color: colorScheme.surfaceContainerLow,
),
appBarTheme: AppBarTheme(
backgroundColor: colorScheme.surface,
elevation: 0,
scrolledUnderElevation: 0,
centerTitle: false,
titleTextStyle: GoogleFonts.inter(
fontSize: 22,
fontWeight: FontWeight.w600,
color: colorScheme.onSurface,
),
),
);
}
}
+346
View File
@@ -0,0 +1,346 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/server_provider.dart';
import '../theme/app_theme.dart';
class AccountView extends StatelessWidget {
final ScrollController scrollController;
const AccountView({super.key, required this.scrollController});
String _formatBytes(int bytes) {
if (bytes <= 0) return '0 GB';
final gb = bytes / (1024 * 1024 * 1024);
return '${gb.toStringAsFixed(2)} GB';
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final provider = context.watch<ServerProvider>();
final quota = provider.quota;
return CustomScrollView(
controller: scrollController,
physics: const BouncingScrollPhysics(),
slivers: [
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Account & Storage',
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
IconButton.filledTonal(
onPressed: () {
_showLogoutConfirmation(context, provider);
},
icon: const Icon(Icons.logout_rounded),
tooltip: 'Log Out',
style: IconButton.styleFrom(
foregroundColor: colorScheme.error,
backgroundColor: colorScheme.errorContainer.withValues(alpha: 0.5),
),
),
],
),
const SizedBox(height: 4),
Text(
'Connected to ${provider.serverUrl}',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 20),
// User Profile & Storage Card
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: colorScheme.primaryContainer.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(28),
border: Border.all(
color: colorScheme.primary.withValues(alpha: 0.2),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
radius: 28,
backgroundColor: colorScheme.primary,
child: Text(
(quota?.userName ?? provider.username).substring(0, 1).toUpperCase(),
style: theme.textTheme.headlineSmall?.copyWith(
color: colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
quota?.userName ?? provider.username,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 2),
Text(
quota?.email ?? provider.username,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: provider.isLoggedIn ? Colors.green.withValues(alpha: 0.2) : Colors.red.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(12),
),
child: Text(
provider.isLoggedIn ? 'ONLINE' : 'OFFLINE',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: provider.isLoggedIn ? Colors.green.shade800 : Colors.red.shade800,
),
),
),
],
),
const SizedBox(height: 20),
const Divider(height: 1),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Storage Quota',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
Text(
quota != null
? (quota.totalBytes > 0
? '${_formatBytes(quota.usedBytes)} of ${_formatBytes(quota.totalBytes)}'
: '${_formatBytes(quota.usedBytes)} (Unlimited)')
: 'Live Server Storage',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w500,
),
),
],
),
const SizedBox(height: 10),
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: LinearProgressIndicator(
value: quota != null && quota.totalBytes > 0 ? quota.usagePercentage : 0.1,
minHeight: 10,
backgroundColor: colorScheme.surfaceContainerHighest,
valueColor: AlwaysStoppedAnimation<Color>(colorScheme.primary),
),
),
const SizedBox(height: 8),
Text(
quota != null
? (quota.totalBytes > 0
? '${(quota.usagePercentage * 100).toStringAsFixed(1)}% used'
: 'Unlimited Storage Plan')
: 'WebDAV connection active',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
),
const SizedBox(height: 24),
// Server Credentials Section
Text(
'Server Connection Info',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
Card(
child: Column(
children: [
ListTile(
leading: const Icon(Icons.dns_rounded),
title: const Text('Nextcloud Host'),
subtitle: Text(provider.serverUrl),
),
const Divider(height: 1, indent: 16, endIndent: 16),
ListTile(
leading: const Icon(Icons.person_rounded),
title: const Text('Logged In User'),
subtitle: Text(provider.username),
),
const Divider(height: 1, indent: 16, endIndent: 16),
ListTile(
leading: const Icon(Icons.refresh_rounded),
title: const Text('Refresh WebDAV Cache'),
onTap: () async {
await provider.refreshData();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Refreshed WebDAV directory data'),
behavior: SnackBarBehavior.floating,
),
);
}
},
),
],
),
),
const SizedBox(height: 24),
// Material You Design Settings
Text(
'Material You Aesthetics',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Dynamic Accent Color Seed',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: AppTheme.seedColors.map((color) {
final isSelected = provider.seedColor == color;
return GestureDetector(
onTap: () => provider.setSeedColor(color),
child: Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: isSelected
? Border.all(color: colorScheme.onSurface, width: 3)
: null,
),
child: isSelected
? const Icon(Icons.check_rounded, color: Colors.white, size: 20)
: null,
),
);
}).toList(),
),
const SizedBox(height: 20),
const Divider(height: 1),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Theme Mode',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
SegmentedButton<ThemeMode>(
segments: const [
ButtonSegment(
value: ThemeMode.system,
icon: Icon(Icons.brightness_auto_rounded),
label: Text('System'),
),
ButtonSegment(
value: ThemeMode.light,
icon: Icon(Icons.light_mode_rounded),
label: Text('Light'),
),
ButtonSegment(
value: ThemeMode.dark,
icon: Icon(Icons.dark_mode_rounded),
label: Text('Dark'),
),
],
selected: {provider.themeMode},
onSelectionChanged: (set) => provider.setThemeMode(set.first),
),
],
),
],
),
),
),
],
),
),
),
const SliverToBoxAdapter(
child: SizedBox(height: 100),
),
],
);
}
void _showLogoutConfirmation(BuildContext context, ServerProvider provider) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Log Out'),
content: Text('Are you sure you want to disconnect from ${provider.serverUrl}?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
style: FilledButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.error,
),
onPressed: () {
Navigator.pop(context);
provider.logout();
},
child: const Text('Log Out'),
),
],
);
},
);
}
}
+151
View File
@@ -0,0 +1,151 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../providers/server_provider.dart';
class ActivityView extends StatelessWidget {
final ScrollController scrollController;
const ActivityView({super.key, required this.scrollController});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final provider = context.watch<ServerProvider>();
final activities = provider.activities;
return CustomScrollView(
controller: scrollController,
physics: const BouncingScrollPhysics(),
slivers: [
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Activity Log',
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(
'Real-time server sync & file events',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
),
if (activities.isEmpty)
SliverFillRemaining(
child: Center(
child: Text(
'No recent activity',
style: theme.textTheme.titleMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
),
)
else
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 20),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final act = activities[index];
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: colorScheme.outlineVariant.withValues(alpha: 0.2),
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: colorScheme.primaryContainer,
shape: BoxShape.circle,
),
child: Icon(
act.icon,
color: colorScheme.onPrimaryContainer,
size: 20,
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
act.title,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
Text(
DateFormat.jm().format(act.timestamp),
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
const SizedBox(height: 4),
Text(
act.subject,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 13,
),
),
const SizedBox(height: 6),
Text(
'By ${act.author} • ${DateFormat.MMMd().format(act.timestamp)}',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.primary,
fontWeight: FontWeight.w500,
fontSize: 11,
),
),
],
),
),
],
),
),
);
},
childCount: activities.length,
),
),
),
const SliverToBoxAdapter(
child: SizedBox(height: 100),
),
],
);
}
}
+672
View File
@@ -0,0 +1,672 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../models/nextcloud_item.dart';
import '../providers/server_provider.dart';
class FilesView extends StatelessWidget {
final ScrollController scrollController;
const FilesView({super.key, required this.scrollController});
String _formatBytes(int bytes) {
if (bytes <= 0) return '0 B';
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
if (bytes < 1024 * 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB';
}
IconData _getItemIcon(NextcloudItemType type) {
switch (type) {
case NextcloudItemType.folder:
return Icons.folder_rounded;
case NextcloudItemType.image:
return Icons.image_rounded;
case NextcloudItemType.video:
return Icons.movie_rounded;
case NextcloudItemType.audio:
return Icons.audiotrack_rounded;
case NextcloudItemType.document:
return Icons.description_rounded;
case NextcloudItemType.archive:
return Icons.folder_zip_rounded;
case NextcloudItemType.file:
return Icons.insert_drive_file_rounded;
}
}
Color _getIconColor(BuildContext context, NextcloudItemType type) {
final colorScheme = Theme.of(context).colorScheme;
switch (type) {
case NextcloudItemType.folder:
return colorScheme.primary;
case NextcloudItemType.image:
return Colors.amber.shade700;
case NextcloudItemType.video:
return Colors.deepOrange.shade600;
case NextcloudItemType.audio:
return Colors.purple.shade600;
case NextcloudItemType.document:
return Colors.blue.shade700;
case NextcloudItemType.archive:
return Colors.teal.shade700;
case NextcloudItemType.file:
return colorScheme.outline;
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final provider = context.watch<ServerProvider>();
return CustomScrollView(
controller: scrollController,
physics: const BouncingScrollPhysics(),
slivers: [
// App Bar / Header
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Nextcloud Files',
style: theme.textTheme.headlineMedium?.copyWith(
color: colorScheme.onSurface,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 2),
Text(
'${provider.username} @ ${provider.serverUrl}',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
Row(
children: [
IconButton.filledTonal(
onPressed: () => _showCreateFolderDialog(context, provider),
icon: const Icon(Icons.create_new_folder_outlined),
tooltip: 'New Folder',
),
const SizedBox(width: 8),
IconButton.filled(
onPressed: () => _showUploadDialog(context, provider),
icon: const Icon(Icons.upload_file_rounded),
tooltip: 'Upload File',
),
],
),
],
),
const SizedBox(height: 16),
// Search & Filter Bar
Row(
children: [
Expanded(
child: Container(
height: 48,
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(24),
),
child: TextField(
onChanged: provider.setSearchQuery,
decoration: InputDecoration(
hintText: 'Search files & folders...',
hintStyle: TextStyle(
color: colorScheme.onSurfaceVariant,
fontSize: 14,
),
prefixIcon: Icon(
Icons.search_rounded,
color: colorScheme.onSurfaceVariant,
),
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(vertical: 12),
),
),
),
),
const SizedBox(width: 8),
FilterChip(
selected: provider.showFavoritesOnly,
label: const Icon(Icons.star_rounded, size: 18),
onSelected: (_) => provider.toggleFavoritesFilter(),
shape: const CircleBorder(),
padding: const EdgeInsets.all(8),
selectedColor: colorScheme.primaryContainer,
),
const SizedBox(width: 4),
IconButton(
onPressed: provider.toggleViewMode,
icon: Icon(
provider.isGridView
? Icons.view_list_rounded
: Icons.grid_view_rounded,
color: colorScheme.onSurfaceVariant,
),
),
],
),
const SizedBox(height: 12),
// Breadcrumbs & Path Navigator
if (provider.pathStack.length > 1)
Row(
children: [
ActionChip(
avatar: const Icon(Icons.arrow_back_rounded, size: 16),
label: const Text('Back'),
onPressed: provider.navigateUp,
backgroundColor: colorScheme.surfaceContainerLow,
),
const SizedBox(width: 8),
Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Text(
provider.currentFolderPath,
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
color: colorScheme.primary,
),
),
),
),
],
),
],
),
),
),
// Files List / Grid
if (provider.isLoading)
const SliverFillRemaining(
child: Center(
child: CircularProgressIndicator(),
),
)
else if (provider.errorMessage != null)
SliverFillRemaining(
child: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error_outline_rounded,
size: 64,
color: colorScheme.error,
),
const SizedBox(height: 16),
Text(
'WebDAV Sync Error',
style: theme.textTheme.titleLarge?.copyWith(
color: colorScheme.error,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
provider.errorMessage!,
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 20),
FilledButton.icon(
onPressed: provider.refreshData,
icon: const Icon(Icons.refresh_rounded),
label: const Text('Retry Connection'),
),
],
),
),
),
)
else if (provider.items.isEmpty)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.folder_open_rounded,
size: 64,
color: colorScheme.outlineVariant,
),
const SizedBox(height: 12),
Text(
'Folder is empty',
style: theme.textTheme.titleMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
)
else if (provider.isGridView)
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
sliver: SliverGrid(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 1.1,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
delegate: SliverChildBuilderDelegate(
(context, index) {
final item = provider.items[index];
return _buildGridCard(context, item, provider);
},
childCount: provider.items.length,
),
),
)
else
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final item = provider.items[index];
return _buildListTile(context, item, provider);
},
childCount: provider.items.length,
),
),
),
const SliverToBoxAdapter(
child: SizedBox(height: 100),
),
],
);
}
Widget _buildListTile(BuildContext context, NextcloudItem item, ServerProvider provider) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Material(
color: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(16),
child: InkWell(
borderRadius: BorderRadius.circular(16),
onTap: () {
if (item.isFolder) {
provider.navigateToFolder(item.path);
} else {
_showFileDetailsSheet(context, item, provider);
}
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: _getIconColor(context, item.type).withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12),
),
child: Icon(
_getItemIcon(item.type),
color: _getIconColor(context, item.type),
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
const SizedBox(height: 2),
Text(
item.isFolder
? 'Folder'
: '${_formatBytes(item.size)} • ${DateFormat.yMMMd().format(item.lastModified)}',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
IconButton(
icon: Icon(
item.isFavorite ? Icons.star_rounded : Icons.star_outline_rounded,
color: item.isFavorite ? Colors.amber.shade700 : colorScheme.outlineVariant,
size: 20,
),
onPressed: () => provider.toggleItemFavorite(item),
),
IconButton(
icon: Icon(
Icons.more_vert_rounded,
color: colorScheme.onSurfaceVariant,
size: 20,
),
onPressed: () => _showFileDetailsSheet(context, item, provider),
),
],
),
),
),
),
);
}
Widget _buildGridCard(BuildContext context, NextcloudItem item, ServerProvider provider) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return Material(
color: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(20),
child: InkWell(
borderRadius: BorderRadius.circular(20),
onTap: () {
if (item.isFolder) {
provider.navigateToFolder(item.path);
} else {
_showFileDetailsSheet(context, item, provider);
}
},
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: _getIconColor(context, item.type).withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12),
),
child: Icon(
_getItemIcon(item.type),
color: _getIconColor(context, item.type),
size: 24,
),
),
IconButton(
icon: Icon(
item.isFavorite ? Icons.star_rounded : Icons.star_outline_rounded,
color: item.isFavorite ? Colors.amber.shade700 : colorScheme.outlineVariant,
size: 20,
),
onPressed: () => provider.toggleItemFavorite(item),
),
],
),
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(
item.isFolder ? 'Folder' : _formatBytes(item.size),
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
],
),
),
),
);
}
void _showFileDetailsSheet(BuildContext context, NextcloudItem item, ServerProvider provider) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
showModalBottomSheet(
context: context,
backgroundColor: colorScheme.surfaceContainerHigh,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(28)),
),
builder: (context) {
return Padding(
padding: const EdgeInsets.fromLTRB(24, 16, 24, 32),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Container(
width: 36,
height: 4,
decoration: BoxDecoration(
color: colorScheme.outlineVariant,
borderRadius: BorderRadius.circular(2),
),
),
),
const SizedBox(height: 20),
Row(
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: _getIconColor(context, item.type).withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(16),
),
child: Icon(
_getItemIcon(item.type),
color: _getIconColor(context, item.type),
size: 28,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 2),
Text(
item.path,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
],
),
const SizedBox(height: 24),
const Divider(height: 1),
const SizedBox(height: 16),
ListTile(
leading: Icon(
item.isFavorite ? Icons.star_rounded : Icons.star_outline_rounded,
color: item.isFavorite ? Colors.amber.shade700 : null,
),
title: Text(item.isFavorite ? 'Remove from Favorites' : 'Add to Favorites'),
onTap: () {
provider.toggleItemFavorite(item);
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.delete_outline_rounded, color: colorScheme.error),
title: Text('Delete from Server', style: TextStyle(color: colorScheme.error)),
onTap: () async {
Navigator.pop(context);
final success = await provider.deleteItem(item.path);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(success ? 'Deleted ${item.name}' : 'Failed to delete ${item.name}'),
behavior: SnackBarBehavior.floating,
),
);
}
},
),
],
),
);
},
);
}
void _showCreateFolderDialog(BuildContext context, ServerProvider provider) {
final controller = TextEditingController();
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Create New Folder'),
content: TextField(
controller: controller,
decoration: const InputDecoration(
labelText: 'Folder Name',
hintText: 'e.g. Finance',
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () async {
final name = controller.text.trim();
if (name.isNotEmpty) {
Navigator.pop(context);
final success = await provider.createFolder(name);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(success ? 'Created folder $name' : 'Failed to create folder'),
behavior: SnackBarBehavior.floating,
),
);
}
}
},
child: const Text('Create'),
),
],
);
},
);
}
void _showUploadDialog(BuildContext context, ServerProvider provider) {
final nameController = TextEditingController();
final contentController = TextEditingController();
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Upload Text File'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: nameController,
decoration: const InputDecoration(
labelText: 'File Name',
hintText: 'notes.txt',
),
),
const SizedBox(height: 12),
TextField(
controller: contentController,
maxLines: 3,
decoration: const InputDecoration(
labelText: 'File Content',
hintText: 'Enter text to upload...',
),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () async {
final name = nameController.text.trim();
final text = contentController.text;
if (name.isNotEmpty) {
Navigator.pop(context);
final bytes = Uint8List.fromList(text.codeUnits);
final success = await provider.uploadFile(name, bytes);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(success ? 'Uploaded $name to Nextcloud' : 'Failed to upload $name'),
behavior: SnackBarBehavior.floating,
),
);
}
}
},
child: const Text('Upload'),
),
],
);
},
);
}
}
+257
View File
@@ -0,0 +1,257 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/server_provider.dart';
class LoginView extends StatefulWidget {
const LoginView({super.key});
@override
State<LoginView> createState() => _LoginViewState();
}
class _LoginViewState extends State<LoginView> {
final _formKey = GlobalKey<FormState>();
final _urlController = TextEditingController(text: 'https://');
final _userController = TextEditingController();
final _passController = TextEditingController();
bool _obscurePassword = true;
@override
void dispose() {
_urlController.dispose();
_userController.dispose();
_passController.dispose();
super.dispose();
}
void _handleLogin() async {
if (!_formKey.currentState!.validate()) return;
FocusScope.of(context).unfocus();
final provider = context.read<ServerProvider>();
final success = await provider.login(
serverUrl: _urlController.text.trim(),
username: _userController.text.trim(),
password: _passController.text,
);
if (!success && mounted) {
final error = provider.errorMessage ?? 'Failed to connect to Nextcloud server.';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(error),
backgroundColor: Theme.of(context).colorScheme.error,
behavior: SnackBarBehavior.floating,
),
);
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final provider = context.watch<ServerProvider>();
return Scaffold(
body: SafeArea(
child: Center(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 440),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header Logo & Branding
Center(
child: Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: colorScheme.primaryContainer,
shape: BoxShape.circle,
),
child: Icon(
Icons.cloud_outlined,
size: 44,
color: colorScheme.onPrimaryContainer,
),
),
),
const SizedBox(height: 24),
Text(
'Nextcloud Client',
textAlign: TextAlign.center,
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w800,
letterSpacing: -0.5,
),
),
const SizedBox(height: 6),
Text(
'Log in to your selfhosted Nextcloud server',
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 36),
// Error Box if any
if (provider.errorMessage != null)
Container(
margin: const EdgeInsets.only(bottom: 20),
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: colorScheme.errorContainer,
borderRadius: BorderRadius.circular(16),
),
child: Row(
children: [
Icon(
Icons.error_outline_rounded,
color: colorScheme.onErrorContainer,
size: 20,
),
const SizedBox(width: 12),
Expanded(
child: Text(
provider.errorMessage!,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onErrorContainer,
fontWeight: FontWeight.w500,
),
),
),
],
),
),
// Server URL Input
TextFormField(
controller: _urlController,
keyboardType: TextInputType.url,
decoration: InputDecoration(
labelText: 'Server Address',
hintText: 'https://cloud.example.com',
prefixIcon: const Icon(Icons.dns_outlined),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
filled: true,
fillColor: colorScheme.surfaceContainerLow,
),
validator: (val) {
if (val == null || val.trim().isEmpty || val == 'https://') {
return 'Please enter your Nextcloud server URL';
}
return null;
},
),
const SizedBox(height: 16),
// Username Input
TextFormField(
controller: _userController,
decoration: InputDecoration(
labelText: 'Username',
prefixIcon: const Icon(Icons.person_outline_rounded),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
filled: true,
fillColor: colorScheme.surfaceContainerLow,
),
validator: (val) {
if (val == null || val.trim().isEmpty) {
return 'Please enter your username';
}
return null;
},
),
const SizedBox(height: 16),
// Password / App Password Input
TextFormField(
controller: _passController,
obscureText: _obscurePassword,
decoration: InputDecoration(
labelText: 'Password or App Password',
prefixIcon: const Icon(Icons.lock_outline_rounded),
suffixIcon: IconButton(
icon: Icon(
_obscurePassword ? Icons.visibility_off_outlined : Icons.visibility_outlined,
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
filled: true,
fillColor: colorScheme.surfaceContainerLow,
),
validator: (val) {
if (val == null || val.isEmpty) {
return 'Please enter your password or app password';
}
return null;
},
),
const SizedBox(height: 28),
// Login Button
SizedBox(
height: 54,
child: FilledButton(
onPressed: provider.isLoading ? null : _handleLogin,
style: FilledButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(27),
),
),
child: provider.isLoading
? SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 2.5,
color: colorScheme.onPrimary,
),
)
: const Text(
'Log In',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
const SizedBox(height: 24),
Text(
'Supports standard WebDAV and OCS APIs for all self-hosted Nextcloud Hub installations.',
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
),
),
),
),
),
);
}
}
+286
View File
@@ -0,0 +1,286 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../models/nextcloud_item.dart';
import '../providers/server_provider.dart';
class PhotosView extends StatelessWidget {
final ScrollController scrollController;
const PhotosView({super.key, required this.scrollController});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final provider = context.watch<ServerProvider>();
final photos = provider.photoItems;
return CustomScrollView(
controller: scrollController,
physics: const BouncingScrollPhysics(),
slivers: [
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Photos & Media',
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(
'${photos.length} cloud photos & video streams',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
),
if (photos.isEmpty)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.photo_library_outlined,
size: 64,
color: colorScheme.outlineVariant,
),
const SizedBox(height: 12),
Text(
'No photos found in Nextcloud library',
style: theme.textTheme.titleMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
)
else
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 16),
sliver: SliverGrid(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
childAspectRatio: 1.0,
),
delegate: SliverChildBuilderDelegate(
(context, index) {
final photo = photos[index];
return _buildPhotoTile(context, photo, provider);
},
childCount: photos.length,
),
),
),
const SliverToBoxAdapter(
child: SizedBox(height: 100),
),
],
);
}
Widget _buildPhotoTile(BuildContext context, NextcloudItem photo, ServerProvider provider) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return GestureDetector(
onTap: () => _openLightbox(context, photo, provider),
child: Container(
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(16),
),
clipBehavior: Clip.antiAlias,
child: Stack(
fit: StackFit.expand,
children: [
photo.previewUrl != null
? Image.network(
photo.previewUrl!,
fit: BoxFit.cover,
errorBuilder: (ctx, err, stack) => _buildFallbackTile(context, photo),
)
: _buildFallbackTile(context, photo),
if (photo.type == NextcloudItemType.video)
Positioned(
bottom: 8,
right: 8,
child: Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.6),
shape: BoxShape.circle,
),
child: const Icon(
Icons.play_arrow_rounded,
color: Colors.white,
size: 16,
),
),
),
if (photo.isFavorite)
const Positioned(
top: 8,
right: 8,
child: Icon(
Icons.star_rounded,
color: Colors.amber,
size: 18,
),
),
],
),
),
);
}
Widget _buildFallbackTile(BuildContext context, NextcloudItem photo) {
final colorScheme = Theme.of(context).colorScheme;
return Container(
color: colorScheme.secondaryContainer,
child: Center(
child: Icon(
photo.type == NextcloudItemType.video
? Icons.movie_rounded
: Icons.image_rounded,
color: colorScheme.onSecondaryContainer,
size: 32,
),
),
);
}
void _openLightbox(BuildContext context, NextcloudItem photo, ServerProvider provider) {
showDialog(
context: context,
barrierColor: Colors.black.withValues(alpha: 0.92),
builder: (context) {
return Dialog.fullscreen(
backgroundColor: Colors.transparent,
child: Stack(
children: [
InteractiveViewer(
minScale: 0.8,
maxScale: 4.0,
child: Center(
child: photo.previewUrl != null
? Image.network(
photo.previewUrl!,
fit: BoxFit.contain,
)
: Icon(
photo.type == NextcloudItemType.video
? Icons.movie_rounded
: Icons.image_rounded,
size: 120,
color: Colors.white70,
),
),
),
Positioned(
top: 24,
left: 16,
right: 16,
child: SafeArea(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton.filledTonal(
onPressed: () => Navigator.pop(context),
icon: const Icon(Icons.close_rounded, color: Colors.white),
style: IconButton.styleFrom(
backgroundColor: Colors.black.withValues(alpha: 0.5),
),
),
Row(
children: [
IconButton.filledTonal(
onPressed: () {
provider.toggleItemFavorite(photo);
},
icon: Icon(
photo.isFavorite ? Icons.star_rounded : Icons.star_outline_rounded,
color: photo.isFavorite ? Colors.amber : Colors.white,
),
style: IconButton.styleFrom(
backgroundColor: Colors.black.withValues(alpha: 0.5),
),
),
const SizedBox(width: 8),
IconButton.filledTonal(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Downloading full resolution ${photo.name}...'),
behavior: SnackBarBehavior.floating,
),
);
},
icon: const Icon(Icons.download_rounded, color: Colors.white),
style: IconButton.styleFrom(
backgroundColor: Colors.black.withValues(alpha: 0.5),
),
),
],
),
],
),
),
),
Positioned(
bottom: 32,
left: 24,
right: 24,
child: SafeArea(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.65),
borderRadius: BorderRadius.circular(24),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
photo.name,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 15,
),
),
const SizedBox(height: 4),
Text(
'${DateFormat.yMMMMd().format(photo.lastModified)} • Nextcloud Photos',
style: const TextStyle(
color: Colors.white70,
fontSize: 12,
),
),
],
),
),
),
),
],
),
);
},
);
}
}
+145
View File
@@ -0,0 +1,145 @@
import 'dart:ui';
import 'package:flutter/material.dart';
class FloatingNavItem {
final String label;
final IconData icon;
final IconData selectedIcon;
final String? badge;
const FloatingNavItem({
required this.label,
required this.icon,
required this.selectedIcon,
this.badge,
});
}
class FloatingBottomNavBar extends StatelessWidget {
final int selectedIndex;
final ValueChanged<int> onDestinationSelected;
final List<FloatingNavItem> items;
final bool isVisible;
const FloatingBottomNavBar({
super.key,
required this.selectedIndex,
required this.onDestinationSelected,
required this.items,
this.isVisible = true,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return AnimatedSlide(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOutCubic,
offset: isVisible ? Offset.zero : const Offset(0, 1.5),
child: AnimatedOpacity(
duration: const Duration(milliseconds: 250),
opacity: isVisible ? 1.0 : 0.0,
child: SafeArea(
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
margin: const EdgeInsets.only(bottom: 20, left: 24, right: 24),
constraints: const BoxConstraints(maxWidth: 460),
height: 68,
child: ClipRRect(
borderRadius: BorderRadius.circular(34),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.82),
borderRadius: BorderRadius.circular(34),
border: Border.all(
color: colorScheme.outlineVariant.withValues(alpha: 0.3),
width: 1,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.12),
blurRadius: 24,
offset: const Offset(0, 8),
),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: List.generate(items.length, (index) {
final item = items[index];
final isSelected = selectedIndex == index;
return Expanded(
child: InkWell(
onTap: () => onDestinationSelected(index),
borderRadius: BorderRadius.circular(28),
splashColor: colorScheme.primary.withValues(alpha: 0.12),
highlightColor: Colors.transparent,
child: AnimatedContainer(
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOutCubic,
margin: const EdgeInsets.symmetric(horizontal: 4),
padding: const EdgeInsets.symmetric(vertical: 6),
decoration: BoxDecoration(
color: isSelected
? colorScheme.primaryContainer
: Colors.transparent,
borderRadius: BorderRadius.circular(24),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
AnimatedScale(
duration: const Duration(milliseconds: 200),
scale: isSelected ? 1.12 : 1.0,
child: Icon(
isSelected ? item.selectedIcon : item.icon,
size: 22,
color: isSelected
? colorScheme.onPrimaryContainer
: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 3),
AnimatedDefaultTextStyle(
duration: const Duration(milliseconds: 200),
style: TextStyle(
fontSize: 11,
fontWeight: isSelected
? FontWeight.w700
: FontWeight.w500,
color: isSelected
? colorScheme.onPrimaryContainer
: colorScheme.onSurfaceVariant,
letterSpacing: 0.1,
),
child: Text(
item.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
),
);
}),
),
),
),
),
),
),
),
),
);
}
}