Troca de desing

This commit is contained in:
Carlos Correia
2026-05-18 15:04:07 +01:00
parent 9b4c2f7e04
commit 9999011cfd
9 changed files with 3000 additions and 2138 deletions

View File

@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import '../constants/item_categories.dart';
import '../theme/app_theme.dart';
class AddItemScreen extends StatefulWidget {
const AddItemScreen({super.key});
@@ -12,143 +13,94 @@ class AddItemScreen extends StatefulWidget {
}
class _AddItemScreenState extends State<AddItemScreen> {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _descriptionController = TextEditingController();
final _nameController = TextEditingController();
final _descController = TextEditingController();
final _imagePicker = ImagePicker();
XFile? _pickedImage;
ItemCategory? _selectedCategory;
Subcategory? _selectedSubcategory;
final Set<String> _selectedTags = {};
XFile? _selectedImage;
bool _isLoading = false;
Future<void> _pickImage(ImageSource source) async {
final picker = ImagePicker();
final image = await picker.pickImage(
source: source,
maxWidth: 1024,
imageQuality: 80,
);
if (image != null) {
setState(() => _selectedImage = image);
}
}
Future<void> _showImageSourcePicker() async {
final source = await showModalBottomSheet<ImageSource>(
context: context,
backgroundColor: Colors.white,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (context) => SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(
Icons.photo_camera,
color: Color(0xFF0066CC),
),
title: const Text('Tirar foto'),
onTap: () => Navigator.pop(context, ImageSource.camera),
),
ListTile(
leading: const Icon(
Icons.photo_library,
color: Color(0xFF0066CC),
),
title: const Text('Escolher da galeria'),
onTap: () => Navigator.pop(context, ImageSource.gallery),
),
],
),
),
),
);
if (source != null) {
await _pickImage(source);
}
}
@override
void dispose() {
_nameController.dispose();
_descriptionController.dispose();
_descController.dispose();
super.dispose();
}
void _onCategoryChanged(ItemCategory? category) {
setState(() {
_selectedCategory = category;
_selectedSubcategory = null;
_selectedTags.clear();
if (category != null && category.subcategories.isNotEmpty) {
_selectedSubcategory = category.subcategories.first;
_autoAssignTags(category.id, category.subcategories.first.id);
Future<void> _pickImage() async {
try {
final image = await _imagePicker.pickImage(
source: ImageSource.gallery,
maxWidth: 1080,
maxHeight: 1080,
imageQuality: 80,
);
if (image != null) {
setState(() => _pickedImage = image);
}
});
} catch (e) {
if (mounted) AppSnack.error(context, 'Erro ao selecionar foto: $e');
}
}
void _onSubcategoryChanged(Subcategory? subcategory) {
setState(() {
_selectedSubcategory = subcategory;
_selectedTags.clear();
if (_selectedCategory != null && subcategory != null) {
_autoAssignTags(_selectedCategory!.id, subcategory.id);
Future<void> _takePhoto() async {
try {
final image = await _imagePicker.pickImage(
source: ImageSource.camera,
maxWidth: 1080,
maxHeight: 1080,
imageQuality: 80,
);
if (image != null) {
setState(() => _pickedImage = image);
}
});
} catch (e) {
if (mounted) AppSnack.error(context, 'Erro ao abrir câmara: $e');
}
}
void _autoAssignTags(String categoryId, String subcategoryId) {
final autoTags = getAutoContextTags(categoryId, subcategoryId);
setState(() {
_selectedTags.addAll(autoTags);
});
}
void _toggleTag(String tagId) {
setState(() {
if (_selectedTags.contains(tagId)) {
_selectedTags.remove(tagId);
} else if (_selectedTags.length < 10) {
_selectedTags.add(tagId);
void _toggleSubcategoryTags(
Subcategory? oldSub,
Subcategory? newSub,
) {
if (oldSub != null && _selectedCategory != null) {
for (final t in getAutoContextTags(_selectedCategory!.id, oldSub.id)) {
_selectedTags.remove(t);
}
});
}
if (newSub != null && _selectedCategory != null) {
_selectedTags.addAll(
getAutoContextTags(_selectedCategory!.id, newSub.id),
);
}
}
Future<void> _saveItem() async {
if (_nameController.text.trim().isEmpty) {
_showErrorSnackBar('Por favor, insira o nome do item');
AppSnack.error(context, 'Indique um nome');
return;
}
if (_selectedCategory == null) {
_showErrorSnackBar('Por favor, selecione uma categoria');
AppSnack.error(context, 'Selecione uma categoria');
return;
}
setState(() => _isLoading = true);
try {
final user = Supabase.instance.client.auth.currentUser;
if (user == null) {
_showErrorSnackBar('Usuário não autenticado');
AppSnack.error(context, 'Utilizador não autenticado');
return;
}
// Ensure user profile row exists in public.users (FK requirement)
await Supabase.instance.client.from('users').upsert({
'id': user.id,
'nome':
user.userMetadata?['username'] ??
'nome': user.userMetadata?['username'] ??
user.email?.split('@').first ??
'Usuário',
'Utilizador',
}, onConflict: 'id');
final inserted = await Supabase.instance.client
@@ -164,11 +116,10 @@ class _AddItemScreenState extends State<AddItemScreen> {
})
.select()
.single();
final itemId = inserted['id'];
// Upload image if selected
if (_selectedImage != null) {
final itemId = inserted['id'];
final file = File(_selectedImage!.path);
if (_pickedImage != null) {
final file = File(_pickedImage!.path);
final fileName =
'item_${itemId}_${DateTime.now().millisecondsSinceEpoch}.jpg';
await Supabase.instance.client.storage
@@ -183,333 +134,348 @@ class _AddItemScreenState extends State<AddItemScreen> {
});
}
_showSuccessSnackBar('Item adicionado com sucesso!');
if (mounted) Navigator.pop(context);
if (mounted) {
AppSnack.success(context, 'Item adicionado!');
Navigator.pop(context);
}
} catch (e) {
_showErrorSnackBar('Erro ao salvar item: $e');
if (mounted) AppSnack.error(context, 'Erro ao guardar: $e');
} finally {
setState(() => _isLoading = false);
if (mounted) setState(() => _isLoading = false);
}
}
void _showErrorSnackBar(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message), backgroundColor: Colors.red),
);
}
void _showSuccessSnackBar(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message), backgroundColor: Colors.green),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFFFE5CC),
backgroundColor: AppColors.background,
appBar: AppBar(
backgroundColor: const Color(0xFF0066CC),
backgroundColor: AppColors.background,
elevation: 0,
title: const Text(
'Adicionar Item',
style: TextStyle(color: Colors.white, fontSize: 20),
),
centerTitle: true,
iconTheme: const IconThemeData(color: AppColors.textPrimary),
title: const Text('Adicionar Item', style: AppText.h3),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Image picker
Center(
child: GestureDetector(
onTap: _showImageSourcePicker,
child: Container(
width: 140,
height: 140,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: const Color(0xFFE0E0E0)),
),
child: _selectedImage != null
? ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.file(
File(_selectedImage!.path),
fit: BoxFit.cover,
),
)
: const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.add_a_photo_outlined,
size: 40,
color: Color(0xFF0066CC),
),
SizedBox(height: 8),
Text(
'Adicionar foto',
style: TextStyle(
color: Color(0xFF666666),
fontSize: 12,
),
),
],
),
),
),
),
const SizedBox(height: 20),
// Name field
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: const Color(0xFFE0E0E0)),
),
child: TextField(
controller: _nameController,
decoration: const InputDecoration(
labelText: 'Nome do item',
hintText: 'Ex: Camiseta Azul',
border: InputBorder.none,
contentPadding: EdgeInsets.symmetric(
horizontal: 16,
vertical: 16,
),
),
),
),
const SizedBox(height: 16),
// Description field
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: const Color(0xFFE0E0E0)),
),
child: TextField(
controller: _descriptionController,
maxLines: 3,
decoration: const InputDecoration(
labelText: 'Descrição (opcional)',
hintText: 'Detalhes sobre o item',
border: InputBorder.none,
contentPadding: EdgeInsets.symmetric(
horizontal: 16,
vertical: 16,
),
),
),
),
_buildImagePicker(),
const SizedBox(height: 24),
// Category selection
const Text(
'Categoria',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Color(0xFF333333),
),
),
const Text('Nome', style: AppText.label),
const SizedBox(height: 8),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: const Color(0xFFE0E0E0)),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<ItemCategory>(
value: _selectedCategory,
hint: const Text('Selecione uma categoria'),
isExpanded: true,
items: itemCategories.map((category) {
return DropdownMenuItem<ItemCategory>(
value: category,
child: Row(
children: [
Text(
category.icon,
style: const TextStyle(fontSize: 24),
),
const SizedBox(width: 12),
Text(category.name),
],
),
);
}).toList(),
onChanged: _onCategoryChanged,
),
),
_textField(
controller: _nameController,
hint: 'ex: Camisa azul',
icon: Icons.label_outline_rounded,
),
const SizedBox(height: 16),
// Subcategory selection
const SizedBox(height: 20),
const Text('Descrição (opcional)', style: AppText.label),
const SizedBox(height: 8),
_textField(
controller: _descController,
hint: 'detalhes do item',
icon: Icons.notes_rounded,
maxLines: 3,
),
const SizedBox(height: 24),
const Text('Categoria', style: AppText.label),
const SizedBox(height: 12),
_buildCategoryGrid(),
if (_selectedCategory != null &&
_selectedCategory!.subcategories.isNotEmpty) ...[
const Text(
'Subcategoria',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Color(0xFF333333),
),
),
const SizedBox(height: 24),
const Text('Subcategoria', style: AppText.label),
const SizedBox(height: 8),
SizedBox(
height: 60,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: _selectedCategory!.subcategories.length,
itemBuilder: (context, index) {
final subcategory = _selectedCategory!.subcategories[index];
final isSelected = _selectedSubcategory == subcategory;
return Padding(
padding: const EdgeInsets.only(right: 8),
child: GestureDetector(
onTap: () => _onSubcategoryChanged(subcategory),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
decoration: BoxDecoration(
color: isSelected
? const Color(0xFF0066CC)
: Colors.white,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: isSelected
? const Color(0xFF0066CC)
: const Color(0xFFE0E0E0),
),
),
child: Center(
child: Text(
subcategory.name,
style: TextStyle(
color: isSelected
? Colors.white
: const Color(0xFF333333),
fontWeight: FontWeight.w500,
),
),
),
),
),
);
},
),
Wrap(
spacing: 8,
runSpacing: 8,
children: _selectedCategory!.subcategories.map((sub) {
final selected = _selectedSubcategory?.id == sub.id;
return AppChip(
label: sub.name,
selected: selected,
color: _selectedCategory!.color,
onTap: () {
setState(() {
final oldSub = _selectedSubcategory;
_selectedSubcategory = selected ? null : sub;
_toggleSubcategoryTags(
oldSub,
_selectedSubcategory,
);
});
},
);
}).toList(),
),
const SizedBox(height: 8),
if (_selectedSubcategory != null)
if (_selectedSubcategory != null) ...[
const SizedBox(height: 6),
Text(
_selectedSubcategory!.examples,
style: const TextStyle(
fontSize: 12,
color: Color(0xFF666666),
_selectedSubcategory!.description,
style: AppText.caption.copyWith(
fontStyle: FontStyle.italic,
),
),
],
],
const SizedBox(height: 24),
// Context tags
const Text(
'Tags de Contexto',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Color(0xFF333333),
),
),
const Text('Tags de Contexto', style: AppText.label),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: contextTags.map((tag) {
final isSelected = _selectedTags.contains(tag.id);
return FilterChip(
label: Text(tag.name),
selected: isSelected,
onSelected: (selected) => _toggleTag(tag.id),
selectedColor: const Color(0xFF0066CC).withValues(alpha: 0.2),
checkmarkColor: const Color(0xFF0066CC),
backgroundColor: Colors.white,
labelStyle: TextStyle(
color: isSelected
? const Color(0xFF0066CC)
: const Color(0xFF333333),
),
final selected = _selectedTags.contains(tag.id);
return AppChip(
label: tag.name,
selected: selected,
onTap: () {
setState(() {
if (selected) {
_selectedTags.remove(tag.id);
} else {
_selectedTags.add(tag.id);
}
});
},
);
}).toList(),
),
const SizedBox(height: 8),
Text(
'Tags selecionadas: ${_selectedTags.length}/10',
style: const TextStyle(fontSize: 12, color: Color(0xFF666666)),
),
const SizedBox(height: 32),
// Save button
SizedBox(
width: double.infinity,
height: 56,
child: ElevatedButton(
onPressed: _isLoading ? null : _saveItem,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF0066CC),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
elevation: 0,
),
child: _isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.white,
),
),
)
: const Text(
'Salvar Item',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
),
AppButton(
label: 'Guardar Item',
icon: Icons.check_rounded,
loading: _isLoading,
onPressed: _saveItem,
),
],
),
),
);
}
Widget _buildImagePicker() {
return Container(
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: BorderRadius.circular(AppRadius.lg),
border: Border.all(color: AppColors.border),
),
clipBehavior: Clip.antiAlias,
child: Column(
children: [
AspectRatio(
aspectRatio: 16 / 11,
child: _pickedImage != null
? Stack(
fit: StackFit.expand,
children: [
Image.file(File(_pickedImage!.path), fit: BoxFit.cover),
Positioned(
top: 8,
right: 8,
child: Material(
color: Colors.black.withValues(alpha: 0.55),
shape: const CircleBorder(),
child: InkWell(
customBorder: const CircleBorder(),
onTap: () => setState(() => _pickedImage = null),
child: const Padding(
padding: EdgeInsets.all(8),
child: Icon(
Icons.close_rounded,
color: Colors.white,
size: 18,
),
),
),
),
),
],
)
: Container(
color: AppColors.surfaceAlt,
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.image_outlined,
size: 48,
color: AppColors.textTertiary,
),
const SizedBox(height: 8),
Text(
'Adicione uma foto',
style: AppText.caption,
),
],
),
),
),
Row(
children: [
Expanded(
child: _imageBtn(
icon: Icons.photo_camera_rounded,
label: 'Câmara',
onTap: _takePhoto,
),
),
Container(width: 1, height: 44, color: AppColors.border),
Expanded(
child: _imageBtn(
icon: Icons.photo_library_rounded,
label: 'Galeria',
onTap: _pickImage,
),
),
],
),
],
),
);
}
Widget _imageBtn({
required IconData icon,
required String label,
required VoidCallback onTap,
}) {
return Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 18, color: AppColors.primary),
const SizedBox(width: 8),
Text(
label,
style: const TextStyle(
color: AppColors.primary,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
);
}
Widget _textField({
required TextEditingController controller,
required String hint,
required IconData icon,
int maxLines = 1,
}) {
return Container(
decoration: AppDecorations.outlined(),
child: TextField(
controller: controller,
maxLines: maxLines,
style: AppText.body,
decoration: InputDecoration(
prefixIcon: maxLines == 1
? Icon(icon, color: AppColors.textSecondary)
: Padding(
padding: const EdgeInsets.only(left: 12, top: 14),
child: Icon(icon, color: AppColors.textSecondary),
),
prefixIconConstraints: maxLines == 1
? null
: const BoxConstraints(minWidth: 40, minHeight: 40),
hintText: hint,
hintStyle: TextStyle(color: AppColors.textTertiary),
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 14,
),
),
),
);
}
Widget _buildCategoryGrid() {
return GridView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: itemCategories.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
childAspectRatio: 1,
),
itemBuilder: (_, i) {
final c = itemCategories[i];
final selected = _selectedCategory?.id == c.id;
return AnimatedContainer(
duration: const Duration(milliseconds: 180),
decoration: BoxDecoration(
color: selected ? c.color : AppColors.surface,
borderRadius: BorderRadius.circular(AppRadius.lg),
border: Border.all(
color: selected ? c.color : AppColors.border,
width: 1.5,
),
boxShadow: selected
? [
BoxShadow(
color: c.color.withValues(alpha: 0.3),
blurRadius: 12,
offset: const Offset(0, 6),
)
]
: null,
),
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(AppRadius.lg),
onTap: () {
setState(() {
if (_selectedCategory?.id != c.id) {
_selectedCategory = c;
_selectedSubcategory = null;
}
});
},
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
c.icon,
size: 28,
color: selected ? Colors.white : c.color,
),
const SizedBox(height: 6),
Text(
c.name,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: selected
? Colors.white
: AppColors.textPrimary,
),
),
],
),
),
),
),
);
},
);
}
}