stats page pagina melhrar
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class LoginController with ChangeNotifier {
|
||||
final FirebaseAuth _auth = FirebaseAuth.instance;
|
||||
// 1. Substituímos o FirebaseAuth pelo cliente do Supabase
|
||||
final SupabaseClient _supabase = Supabase.instance.client;
|
||||
|
||||
final TextEditingController emailController = TextEditingController();
|
||||
final TextEditingController passwordController = TextEditingController();
|
||||
@@ -22,6 +23,7 @@ class LoginController with ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
// --- VALIDAÇÕES (Mantêm-se iguais) ---
|
||||
String? validateEmail(String? value) {
|
||||
if (value == null || value.isEmpty) return 'Por favor, insira o seu email';
|
||||
final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
|
||||
@@ -37,10 +39,17 @@ class LoginController with ChangeNotifier {
|
||||
|
||||
// --- MÉTODO PARA ENTRAR (LOGIN) ---
|
||||
Future<bool> login() async {
|
||||
_emailError = validateEmail(emailController.text);
|
||||
_passwordError = validatePassword(passwordController.text);
|
||||
// Limpa erros anteriores
|
||||
_emailError = null;
|
||||
_passwordError = null;
|
||||
|
||||
// Valida localmente primeiro
|
||||
String? emailValidation = validateEmail(emailController.text);
|
||||
String? passValidation = validatePassword(passwordController.text);
|
||||
|
||||
if (_emailError != null || _passwordError != null) {
|
||||
if (emailValidation != null || passValidation != null) {
|
||||
_emailError = emailValidation;
|
||||
_passwordError = passValidation;
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
@@ -49,16 +58,25 @@ class LoginController with ChangeNotifier {
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
await _auth.signInWithEmailAndPassword(
|
||||
// 2. Chamada ao Supabase para Login
|
||||
await _supabase.auth.signInWithPassword(
|
||||
email: emailController.text.trim(),
|
||||
password: passwordController.text.trim(),
|
||||
);
|
||||
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
return true;
|
||||
} on FirebaseAuthException catch (e) {
|
||||
|
||||
} on AuthException catch (e) {
|
||||
// 3. Captura erros específicos do Supabase
|
||||
_isLoading = false;
|
||||
_handleFirebaseError(e.code);
|
||||
_handleSupabaseError(e);
|
||||
notifyListeners();
|
||||
return false;
|
||||
} catch (e) {
|
||||
_isLoading = false;
|
||||
_emailError = 'Ocorreu um erro inesperado.';
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
@@ -66,10 +84,15 @@ class LoginController with ChangeNotifier {
|
||||
|
||||
// --- MÉTODO PARA CRIAR CONTA (SIGN UP) ---
|
||||
Future<bool> signUp() async {
|
||||
_emailError = validateEmail(emailController.text);
|
||||
_passwordError = validatePassword(passwordController.text);
|
||||
_emailError = null;
|
||||
_passwordError = null;
|
||||
|
||||
if (_emailError != null || _passwordError != null) {
|
||||
String? emailValidation = validateEmail(emailController.text);
|
||||
String? passValidation = validatePassword(passwordController.text);
|
||||
|
||||
if (emailValidation != null || passValidation != null) {
|
||||
_emailError = emailValidation;
|
||||
_passwordError = passValidation;
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
@@ -78,40 +101,46 @@ class LoginController with ChangeNotifier {
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
await _auth.createUserWithEmailAndPassword(
|
||||
// 4. Chamada ao Supabase para Registo
|
||||
await _supabase.auth.signUp(
|
||||
email: emailController.text.trim(),
|
||||
password: passwordController.text.trim(),
|
||||
);
|
||||
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
return true;
|
||||
} on FirebaseAuthException catch (e) {
|
||||
|
||||
} on AuthException catch (e) {
|
||||
_isLoading = false;
|
||||
_handleFirebaseError(e.code);
|
||||
_handleSupabaseError(e);
|
||||
notifyListeners();
|
||||
return false;
|
||||
} catch (e) {
|
||||
_isLoading = false;
|
||||
_emailError = 'Ocorreu um erro inesperado.';
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void _handleFirebaseError(String code) {
|
||||
switch (code) {
|
||||
case 'email-already-in-use':
|
||||
_emailError = 'Este e-mail já está a ser utilizado.';
|
||||
break;
|
||||
case 'invalid-credential':
|
||||
_emailError = 'E-mail ou password incorretos.';
|
||||
break;
|
||||
case 'user-not-found':
|
||||
_emailError = 'Utilizador não encontrado.';
|
||||
break;
|
||||
case 'wrong-password':
|
||||
_passwordError = 'Palavra-passe incorreta.';
|
||||
break;
|
||||
case 'weak-password':
|
||||
_passwordError = 'A password é demasiado fraca.';
|
||||
break;
|
||||
default:
|
||||
_emailError = 'Erro: $code';
|
||||
// --- TRATAMENTO DE ERROS SUPABASE ---
|
||||
void _handleSupabaseError(AuthException error) {
|
||||
// O Supabase retorna mensagens em inglês, vamos traduzir as mais comuns.
|
||||
// O 'message' contém o texto do erro.
|
||||
final msg = error.message.toLowerCase();
|
||||
|
||||
if (msg.contains('invalid login credentials')) {
|
||||
_emailError = 'E-mail ou password incorretos.';
|
||||
} else if (msg.contains('user already registered') || msg.contains('already exists')) {
|
||||
_emailError = 'Este e-mail já está registado.';
|
||||
} else if (msg.contains('password')) {
|
||||
_passwordError = 'A password deve ter pelo menos 6 caracteres.';
|
||||
} else if (msg.contains('email')) {
|
||||
_emailError = 'Formato de e-mail inválido.';
|
||||
} else {
|
||||
// Fallback para mostrar a mensagem original se não conhecermos o erro
|
||||
_emailError = error.message;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,18 @@
|
||||
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class RegisterController with ChangeNotifier {
|
||||
final FirebaseAuth _auth = FirebaseAuth.instance;
|
||||
class RegisterController extends ChangeNotifier {
|
||||
// Chave para identificar e validar o formulário
|
||||
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
|
||||
|
||||
final TextEditingController emailController = TextEditingController();
|
||||
final TextEditingController passwordController = TextEditingController();
|
||||
final TextEditingController confirmPasswordController = TextEditingController();
|
||||
|
||||
bool _isLoading = false;
|
||||
String? _emailError;
|
||||
String? _passwordError;
|
||||
String? _confirmPasswordError; // Novo!
|
||||
String? get confirmPasswordError => _confirmPasswordError; // Novo!
|
||||
final nameController = TextEditingController();
|
||||
final emailController = TextEditingController();
|
||||
final passwordController = TextEditingController();
|
||||
final confirmPasswordController = TextEditingController(); // Novo campo
|
||||
|
||||
bool get isLoading => _isLoading;
|
||||
String? get emailError => _emailError;
|
||||
String? get passwordError => _passwordError;
|
||||
bool isLoading = false;
|
||||
|
||||
// Validações
|
||||
// --- AS TUAS VALIDAÇÕES ---
|
||||
String? validateEmail(String? value) {
|
||||
if (value == null || value.isEmpty) return 'Por favor, insira o seu email';
|
||||
final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
|
||||
@@ -32,6 +25,7 @@ class RegisterController with ChangeNotifier {
|
||||
if (value.length < 6) return 'A password deve ter pelo menos 6 caracteres';
|
||||
return null;
|
||||
}
|
||||
|
||||
String? validateConfirmPassword(String? value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Por favor, confirme a sua password';
|
||||
@@ -41,57 +35,56 @@ class RegisterController with ChangeNotifier {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------
|
||||
|
||||
// MÉTODO PARA CRIAR CONTA (SIGN UP)
|
||||
Future<bool> signUp() async {
|
||||
_emailError = validateEmail(emailController.text);
|
||||
_passwordError = validatePassword(passwordController.text);
|
||||
_emailError = validateEmail(emailController.text);
|
||||
_passwordError = validatePassword(passwordController.text);
|
||||
_confirmPasswordError = validateConfirmPassword(confirmPasswordController.text); // Valida aqui!
|
||||
|
||||
if (_emailError != null || _passwordError != null || _confirmPasswordError != null) {
|
||||
notifyListeners();
|
||||
return false;
|
||||
Future<void> signUp(BuildContext context) async {
|
||||
// 1. Verifica se o formulário é válido antes de fazer qualquer coisa
|
||||
if (!formKey.currentState!.validate()) {
|
||||
return;
|
||||
}
|
||||
|
||||
_isLoading = true;
|
||||
isLoading = true;
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
await _auth.createUserWithEmailAndPassword(
|
||||
final AuthResponse res = await Supabase.instance.client.auth.signUp(
|
||||
email: emailController.text.trim(),
|
||||
password: passwordController.text.trim(),
|
||||
data: {'full_name': nameController.text.trim()},
|
||||
);
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
return true;
|
||||
} on FirebaseAuthException catch (e) {
|
||||
_isLoading = false;
|
||||
_handleFirebaseError(e.code);
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void _handleFirebaseError(String code) {
|
||||
switch (code) {
|
||||
case 'email-already-in-use':
|
||||
_emailError = 'Este e-mail já está a ser utilizado.';
|
||||
break;
|
||||
case 'weak-password':
|
||||
_passwordError = 'A password é demasiado fraca.';
|
||||
break;
|
||||
default:
|
||||
_emailError = 'Erro ao registar: $code';
|
||||
final user = res.user;
|
||||
|
||||
if (user != null && context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Conta criada! Podes fazer login.')),
|
||||
);
|
||||
Navigator.pop(context);
|
||||
}
|
||||
} on AuthException catch (e) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(e.message), backgroundColor: Colors.red),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Erro inesperado'), backgroundColor: Colors.red),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
isLoading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
nameController.dispose();
|
||||
emailController.dispose();
|
||||
passwordController.dispose();
|
||||
confirmPasswordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,146 +1,114 @@
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import '../models/person_model.dart';
|
||||
|
||||
class StatsController {
|
||||
final FirebaseFirestore _db = FirebaseFirestore.instance;
|
||||
final SupabaseClient _supabase = Supabase.instance.client;
|
||||
|
||||
// --- LÓGICA DE FIREBASE ---
|
||||
// --- 1. LER DADOS (STREAM) ---
|
||||
Stream<List<Person>> getMembers(String teamId) {
|
||||
return _supabase
|
||||
.from('members')
|
||||
.stream(primaryKey: ['id'])
|
||||
.eq('team_id', teamId)
|
||||
.order('name', ascending: true) // Ordena por nome
|
||||
.map((data) => data.map((json) => Person.fromMap(json)).toList());
|
||||
}
|
||||
|
||||
// GRAVAR: Cria o personagem numa sub-coleção dentro da equipa
|
||||
Future<void> addPerson(String teamId, String name, String type, String number) async {
|
||||
await _db.collection('teams').doc(teamId).collection('members').add({
|
||||
// --- 2. AÇÕES DE BASE DE DADOS ---
|
||||
|
||||
// Adicionar
|
||||
Future<void> _addPersonToSupabase(String teamId, String name, String type, String number) async {
|
||||
await _supabase.from('members').insert({
|
||||
'team_id': teamId,
|
||||
'name': name,
|
||||
'type': type,
|
||||
'number': number,
|
||||
'createdAt': FieldValue.serverTimestamp(),
|
||||
});
|
||||
}
|
||||
|
||||
// LER: Vai buscar todos os membros da equipa em tempo real
|
||||
Stream<List<Person>> getMembers(String teamId) {
|
||||
return _db
|
||||
.collection('teams')
|
||||
.doc(teamId)
|
||||
.collection('members')
|
||||
.orderBy('createdAt', descending: false) // Organiza por ordem de criação
|
||||
.snapshots()
|
||||
.map((snapshot) => snapshot.docs
|
||||
.map((doc) => Person.fromFirestore(doc.data(), doc.id))
|
||||
.toList());
|
||||
// Editar
|
||||
Future<void> _updatePersonInSupabase(String personId, String name, String type, String number) async {
|
||||
await _supabase.from('members').update({
|
||||
'name': name,
|
||||
'type': type,
|
||||
'number': number,
|
||||
}).eq('id', personId);
|
||||
}
|
||||
// --- Adiciona estas funções dentro da classe StatsController ---
|
||||
|
||||
// ELIMINAR: Remove o documento da sub-coleção
|
||||
Future<void> deletePerson(String teamId, String personId) async {
|
||||
await _db
|
||||
.collection('teams')
|
||||
.doc(teamId)
|
||||
.collection('members')
|
||||
.doc(personId)
|
||||
.delete();
|
||||
}
|
||||
// Apagar
|
||||
Future<void> deletePerson(String teamId, String personId) async {
|
||||
try {
|
||||
await _supabase.from('members').delete().eq('id', personId);
|
||||
} catch (e) {
|
||||
debugPrint("Erro ao apagar: $e");
|
||||
}
|
||||
}
|
||||
|
||||
// EDITAR (LOGICA): Abre o popup já preenchido com os dados atuais
|
||||
void showEditPersonDialog(BuildContext context, String teamId, Person person) {
|
||||
final nameController = TextEditingController(text: person.name);
|
||||
final numberController = TextEditingController(text: person.number);
|
||||
String selectedType = person.type;
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => StatefulBuilder(
|
||||
builder: (context, setPopupState) => AlertDialog(
|
||||
title: const Text("Editar Personagem"),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
DropdownButtonFormField<String>(
|
||||
value: selectedType,
|
||||
items: ['Jogador', 'Treinador'].map((t) => DropdownMenuItem(value: t, child: Text(t))).toList(),
|
||||
onChanged: (val) => setPopupState(() => selectedType = val!),
|
||||
decoration: const InputDecoration(labelText: 'Tipo'),
|
||||
),
|
||||
TextField(controller: nameController, decoration: const InputDecoration(labelText: 'Nome')),
|
||||
if (selectedType == 'Jogador')
|
||||
TextField(controller: numberController, decoration: const InputDecoration(labelText: 'Número')),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text("Cancelar")),
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
await _db.collection('teams').doc(teamId).collection('members').doc(person.id).update({
|
||||
'name': nameController.text,
|
||||
'type': selectedType,
|
||||
'number': selectedType == 'Jogador' ? numberController.text : '',
|
||||
});
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
child: const Text("Guardar Alterações"),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// --- LÓGICA DE INTERFACE (POPUP) ---
|
||||
// --- 3. DIÁLOGOS (UI) ---
|
||||
|
||||
// Mostrar Diálogo de Adicionar
|
||||
void showAddPersonDialog(BuildContext context, String teamId) {
|
||||
String selectedType = 'Jogador';
|
||||
final TextEditingController nameController = TextEditingController();
|
||||
final TextEditingController numberController = TextEditingController();
|
||||
_showPersonDialog(context, teamId: teamId);
|
||||
}
|
||||
|
||||
// Mostrar Diálogo de Editar
|
||||
void showEditPersonDialog(BuildContext context, String teamId, Person person) {
|
||||
_showPersonDialog(context, teamId: teamId, person: person);
|
||||
}
|
||||
|
||||
// Função Genérica para o Diálogo (Serve para criar e editar)
|
||||
void _showPersonDialog(BuildContext context, {required String teamId, Person? person}) {
|
||||
final isEditing = person != null;
|
||||
final nameController = TextEditingController(text: person?.name ?? '');
|
||||
final numberController = TextEditingController(text: person?.number ?? '');
|
||||
|
||||
// Valor inicial do dropdown ('Jogador' por defeito)
|
||||
String selectedType = person?.type ?? 'Jogador';
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
// Usamos StatefulBuilder para atualizar o Dropdown dentro do Dialog
|
||||
return StatefulBuilder(
|
||||
builder: (context, setPopupState) {
|
||||
builder: (context, setState) {
|
||||
return AlertDialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
|
||||
title: const Text('Novo Personagem'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Seletor: Jogador ou Treinador
|
||||
DropdownButtonFormField<String>(
|
||||
value: selectedType,
|
||||
decoration: const InputDecoration(labelText: 'Tipo'),
|
||||
items: ['Jogador', 'Treinador']
|
||||
.map((t) => DropdownMenuItem(value: t, child: Text(t)))
|
||||
.toList(),
|
||||
onChanged: (val) {
|
||||
setPopupState(() {
|
||||
selectedType = val!;
|
||||
});
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 15),
|
||||
// Campo Nome
|
||||
TextField(
|
||||
controller: nameController,
|
||||
textCapitalization: TextCapitalization.words,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nome Completo',
|
||||
hintText: 'Ex: Stephen Curry',
|
||||
),
|
||||
),
|
||||
// Campo Número (Aparece apenas se for Jogador)
|
||||
if (selectedType == 'Jogador') ...[
|
||||
const SizedBox(height: 15),
|
||||
TextField(
|
||||
controller: numberController,
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Número da Camisola',
|
||||
hintText: 'Ex: 30',
|
||||
),
|
||||
),
|
||||
title: Text(isEditing ? 'Editar Membro' : 'Novo Membro'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Nome
|
||||
TextField(
|
||||
controller: nameController,
|
||||
decoration: const InputDecoration(labelText: 'Nome'),
|
||||
textCapitalization: TextCapitalization.sentences,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
|
||||
// Tipo (Jogador/Treinador)
|
||||
DropdownButtonFormField<String>(
|
||||
value: selectedType,
|
||||
decoration: const InputDecoration(labelText: 'Função'),
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'Jogador', child: Text('Jogador')),
|
||||
DropdownMenuItem(value: 'Treinador', child: Text('Treinador')),
|
||||
],
|
||||
],
|
||||
),
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
setState(() => selectedType = value);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
|
||||
// Número (Só aparece se for Jogador)
|
||||
if (selectedType == 'Jogador')
|
||||
TextField(
|
||||
controller: numberController,
|
||||
decoration: const InputDecoration(labelText: 'Número da Camisola'),
|
||||
keyboardType: TextInputType.number,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
@@ -148,23 +116,22 @@ void showEditPersonDialog(BuildContext context, String teamId, Person person) {
|
||||
child: const Text('Cancelar'),
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: const Color(0xFF00C853),
|
||||
),
|
||||
style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF00C853)),
|
||||
onPressed: () async {
|
||||
if (nameController.text.isNotEmpty) {
|
||||
// CHAMA A FUNÇÃO DE GRAVAR DO FIREBASE
|
||||
await addPerson(
|
||||
teamId,
|
||||
nameController.text,
|
||||
selectedType,
|
||||
selectedType == 'Jogador' ? numberController.text : '',
|
||||
);
|
||||
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
if (nameController.text.isEmpty) return;
|
||||
|
||||
final name = nameController.text.trim();
|
||||
final number = numberController.text.trim();
|
||||
|
||||
if (isEditing) {
|
||||
await _updatePersonInSupabase(person!.id, name, selectedType, number);
|
||||
} else {
|
||||
await _addPersonToSupabase(teamId, name, selectedType, number);
|
||||
}
|
||||
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
child: const Text('Guardar', style: TextStyle(color: Colors.white)),
|
||||
child: Text(isEditing ? 'Guardar' : 'Adicionar', style: const TextStyle(color: Colors.white)),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1,31 +1,37 @@
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:playmaker/service/auth_service.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
|
||||
class TeamController {
|
||||
final AuthService _authService = AuthService();
|
||||
final CollectionReference _teamsRef = FirebaseFirestore.instance.collection('teams');
|
||||
// Acesso ao cliente do Supabase
|
||||
final SupabaseClient _supabase = Supabase.instance.client;
|
||||
|
||||
// --- STREAM DE EQUIPAS (LER) ---
|
||||
// Retorna uma Lista de Mapas em tempo real
|
||||
Stream<List<Map<String, dynamic>>> get teamsStream {
|
||||
final user = _supabase.auth.currentUser;
|
||||
|
||||
if (user == null) {
|
||||
return const Stream.empty();
|
||||
}
|
||||
|
||||
Stream<QuerySnapshot> get teamsStream {
|
||||
final uid = _authService.currentUid;
|
||||
return _teamsRef
|
||||
.where('userId', isEqualTo: uid)
|
||||
.orderBy('createdAt', descending: true)
|
||||
.snapshots();
|
||||
return _supabase
|
||||
.from('teams')
|
||||
.stream(primaryKey: ['id']) // É obrigatório definir a Primary Key para Streams
|
||||
.eq('user_id', user.id) // Filtra apenas as equipas do utilizador logado
|
||||
.order('created_at', ascending: false);
|
||||
}
|
||||
|
||||
// --- CRIAR EQUIPA ---
|
||||
Future<void> createTeam(String name, String season, String imageUrl) async {
|
||||
final uid = _authService.currentUid;
|
||||
final user = _supabase.auth.currentUser;
|
||||
|
||||
if (uid != null) {
|
||||
if (user != null) {
|
||||
try {
|
||||
await _teamsRef.add({
|
||||
await _supabase.from('teams').insert({
|
||||
'name': name,
|
||||
'season': season,
|
||||
'imageUrl': imageUrl,
|
||||
'userId': uid,
|
||||
'createdAt': FieldValue.serverTimestamp(),
|
||||
'image_url': imageUrl, // Garante que na tabela a coluna se chama 'image_url' (snake_case)
|
||||
'user_id': user.id, // Chave estrangeira para ligar ao utilizador
|
||||
// 'created_at': O Supabase preenche isto sozinho se tiver default: now()
|
||||
});
|
||||
} catch (e) {
|
||||
print("Erro ao criar equipa: $e");
|
||||
@@ -34,15 +40,32 @@ class TeamController {
|
||||
print("Erro: Utilizador não autenticado.");
|
||||
}
|
||||
}
|
||||
|
||||
// --- ELIMINAR EQUIPA ---
|
||||
Future<void> deleteTeam(String docId) async {
|
||||
try {
|
||||
await _teamsRef.doc(docId).delete();
|
||||
// Se configuraste "ON DELETE CASCADE" no Supabase, isto apaga também os jogadores
|
||||
await _supabase.from('teams').delete().eq('id', docId);
|
||||
} catch (e) {
|
||||
print("Erro ao eliminar: $e");
|
||||
}
|
||||
Future<int> getPlayerCount(String teamId) async {
|
||||
var snapshot = await _teamsRef.doc(teamId).collection('players').get();
|
||||
return snapshot.docs.length;
|
||||
}
|
||||
}
|
||||
|
||||
// --- CONTAR JOGADORES ---
|
||||
// No SQL não entramos dentro da equipa. Vamos à tabela 'members' e filtramos pelo team_id.
|
||||
// --- CONTAR JOGADORES (CORRIGIDO) ---
|
||||
Future<int> getPlayerCount(String teamId) async {
|
||||
try {
|
||||
// Correção: O Supabase agora retorna o 'int' diretamente, não um objeto response
|
||||
final int count = await _supabase
|
||||
.from('members')
|
||||
.count(CountOption.exact) // Pede o número exato
|
||||
.eq('team_id', teamId);
|
||||
|
||||
return count;
|
||||
} catch (e) {
|
||||
print("Erro ao contar jogadores: $e");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
// File generated by FlutterFire CLI.
|
||||
// ignore_for_file: type=lint
|
||||
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
|
||||
import 'package:flutter/foundation.dart'
|
||||
show defaultTargetPlatform, kIsWeb, TargetPlatform;
|
||||
|
||||
/// Default [FirebaseOptions] for use with your Firebase apps.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// import 'firebase_options.dart';
|
||||
/// // ...
|
||||
/// await Firebase.initializeApp(
|
||||
/// options: DefaultFirebaseOptions.currentPlatform,
|
||||
/// );
|
||||
/// ```
|
||||
class DefaultFirebaseOptions {
|
||||
static FirebaseOptions get currentPlatform {
|
||||
if (kIsWeb) {
|
||||
return web;
|
||||
}
|
||||
switch (defaultTargetPlatform) {
|
||||
case TargetPlatform.android:
|
||||
return android;
|
||||
case TargetPlatform.iOS:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for ios - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
case TargetPlatform.macOS:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for macos - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
case TargetPlatform.windows:
|
||||
return windows;
|
||||
case TargetPlatform.linux:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for linux - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
default:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions are not supported for this platform.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static const FirebaseOptions web = FirebaseOptions(
|
||||
apiKey: 'AIzaSyBkHZtox18LRzXWYHEKVEXaYkkf8jv8Enk',
|
||||
appId: '1:74256198630:web:ba3d62a31608d686d18427',
|
||||
messagingSenderId: '74256198630',
|
||||
projectId: 'playmaker-9e0fc',
|
||||
authDomain: 'playmaker-9e0fc.firebaseapp.com',
|
||||
databaseURL: 'https://playmaker-9e0fc-default-rtdb.firebaseio.com',
|
||||
storageBucket: 'playmaker-9e0fc.firebasestorage.app',
|
||||
measurementId: 'G-QQE1EZWZ8K',
|
||||
);
|
||||
|
||||
static const FirebaseOptions android = FirebaseOptions(
|
||||
apiKey: 'AIzaSyDm7MBJQ6vZEE_gM1Ek5LH3Mf5ui2YHc2I',
|
||||
appId: '1:74256198630:android:145e08f6bc85ff13d18427',
|
||||
messagingSenderId: '74256198630',
|
||||
projectId: 'playmaker-9e0fc',
|
||||
databaseURL: 'https://playmaker-9e0fc-default-rtdb.firebaseio.com',
|
||||
storageBucket: 'playmaker-9e0fc.firebasestorage.app',
|
||||
);
|
||||
|
||||
static const FirebaseOptions windows = FirebaseOptions(
|
||||
apiKey: 'AIzaSyBkHZtox18LRzXWYHEKVEXaYkkf8jv8Enk',
|
||||
appId: '1:74256198630:web:6458f24490c3dc80d18427',
|
||||
messagingSenderId: '74256198630',
|
||||
projectId: 'playmaker-9e0fc',
|
||||
authDomain: 'playmaker-9e0fc.firebaseapp.com',
|
||||
databaseURL: 'https://playmaker-9e0fc-default-rtdb.firebaseio.com',
|
||||
storageBucket: 'playmaker-9e0fc.firebasestorage.app',
|
||||
measurementId: 'G-D56MT819B0',
|
||||
);
|
||||
}
|
||||
@@ -1,31 +1,34 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'firebase_options.dart';
|
||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||
import 'pages/login.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await Firebase.initializeApp(
|
||||
options: DefaultFirebaseOptions.currentPlatform,
|
||||
|
||||
await Supabase.initialize(
|
||||
url: 'https://sihwjdshexjyvsbettcd.supabase.co',
|
||||
anonKey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNpaHdqZHNoZXhqeXZzYmV0dGNkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Njg5MTQxMjgsImV4cCI6MjA4NDQ5MDEyOH0.gW3AvTJVNyE1Dqa72OTnhrUIKsndexrY3pKxMIAaAy8', // Uma string longa
|
||||
|
||||
);
|
||||
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false, // Opcional: remove a faixa de debug
|
||||
title: 'BasketTrack',
|
||||
debugShowCheckedModeBanner: false,
|
||||
title: 'PlayMaker',
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: const Color(0xFFE74C3C),
|
||||
seedColor: const Color(0xFFE74C3C),
|
||||
),
|
||||
useMaterial3: true,
|
||||
),
|
||||
),
|
||||
home: const LoginPage(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
class Person {
|
||||
final String id;
|
||||
final String teamId;
|
||||
final String name;
|
||||
final String type; // 'Jogador' ou 'Treinador'
|
||||
final String number; // Ex: '30'
|
||||
final String number;
|
||||
|
||||
Person({required this.id, required this.name, required this.type, required this.number});
|
||||
Person({
|
||||
required this.id,
|
||||
required this.teamId,
|
||||
required this.name,
|
||||
required this.type,
|
||||
required this.number,
|
||||
});
|
||||
|
||||
factory Person.fromFirestore(Map<String, dynamic> data, String id) {
|
||||
// Converter do Supabase (Map) para o Objeto
|
||||
factory Person.fromMap(Map<String, dynamic> map) {
|
||||
return Person(
|
||||
id: id,
|
||||
name: data['name'] ?? '',
|
||||
type: data['type'] ?? 'Jogador',
|
||||
number: data['number'] ?? '',
|
||||
id: map['id'] ?? '',
|
||||
teamId: map['team_id'] ?? '',
|
||||
name: map['name'] ?? '',
|
||||
type: map['type'] ?? 'Jogador',
|
||||
number: map['number']?.toString() ?? '',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../Controllers/register_controller.dart';
|
||||
import '../controllers/register_controller.dart';
|
||||
import '../widgets/register_widgets.dart';
|
||||
import 'home.dart';
|
||||
|
||||
class RegisterPage extends StatefulWidget {
|
||||
const RegisterPage({super.key});
|
||||
@@ -11,67 +10,42 @@ class RegisterPage extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _RegisterPageState extends State<RegisterPage> {
|
||||
final RegisterController controller = RegisterController();
|
||||
// Instancia o controller
|
||||
final RegisterController _controller = RegisterController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
controller.dispose();
|
||||
_controller.dispose(); // Limpa a memória ao sair
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.white,
|
||||
// AppBar para poder voltar atrás
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
foregroundColor: Colors.black,
|
||||
),
|
||||
body: SafeArea(
|
||||
child: ListenableBuilder(
|
||||
listenable: controller,
|
||||
builder: (context, child) {
|
||||
return LayoutBuilder(
|
||||
// ... dentro do LayoutBuilder
|
||||
builder: (context, constraints) {
|
||||
final screenWidth = constraints.maxWidth;
|
||||
|
||||
return Center(
|
||||
child: SingleChildScrollView(
|
||||
child: Container(
|
||||
|
||||
width: screenWidth * 0.6,
|
||||
constraints: const BoxConstraints(minWidth: 320),
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const RegisterHeader(),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
RegisterFormFields(controller: controller),
|
||||
const SizedBox(height: 32),
|
||||
|
||||
RegisterButton(
|
||||
controller: controller,
|
||||
onRegisterSuccess: () {
|
||||
Navigator.pushAndRemoveUntil(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) => const HomeScreen()),
|
||||
(route) => false,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
appBar: AppBar(title: const Text("Criar Conta")),
|
||||
body: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: ListenableBuilder(
|
||||
listenable: _controller, // Ouve as mudanças (loading)
|
||||
builder: (context, child) {
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Text(
|
||||
"Junta-te à Equipa!",
|
||||
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 30),
|
||||
|
||||
// Widgets Extraídos
|
||||
RegisterFormFields(controller: _controller),
|
||||
const SizedBox(height: 24),
|
||||
RegisterButton(controller: _controller),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:playmaker/classe/home.config.dart';
|
||||
import 'package:playmaker/controllers/team_controllers.dart';
|
||||
import 'package:playmaker/grafico%20de%20pizza/grafico.dart';
|
||||
import 'package:playmaker/pages/teams_page.dart';
|
||||
// Certifica-te que o caminho do controller está correto:
|
||||
|
||||
class HomeScreen extends StatefulWidget {
|
||||
const HomeScreen({super.key});
|
||||
@@ -12,19 +13,20 @@ class HomeScreen extends StatefulWidget {
|
||||
|
||||
class _HomeScreenState extends State<HomeScreen> {
|
||||
int _selectedIndex = 0;
|
||||
|
||||
// 1. Instanciar o Controller para aceder ao Supabase
|
||||
final TeamController _teamController = TeamController();
|
||||
|
||||
// Lista de Widgets para cada aba
|
||||
// O IndexedStack vai alternar entre estes 4 widgets
|
||||
late final List<Widget> _pages;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_pages = [
|
||||
_buildHomeContent(), // Index 0
|
||||
const Center(child: Text('Tela de Jogo')), // Index 1
|
||||
const TeamsPage(), // Index 2 (TUA TELA DE EQUIPAS)
|
||||
const Center(child: Text('Tela de Status')), // Index 3
|
||||
_buildHomeContent(), // Index 0: Home
|
||||
const Center(child: Text('Tela de Jogo')), // Index 1: Jogo
|
||||
_buildTeamsContent(), // Index 2: Equipas (O teu StreamBuilder entra aqui)
|
||||
const Center(child: Text('Tela de Status')), // Index 3: Status
|
||||
];
|
||||
}
|
||||
|
||||
@@ -34,8 +36,6 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
});
|
||||
}
|
||||
|
||||
//home
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
@@ -50,7 +50,6 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
),
|
||||
),
|
||||
|
||||
// O IndexedStack mantém todas as páginas "vivas" mas só mostra uma
|
||||
body: IndexedStack(
|
||||
index: _selectedIndex,
|
||||
children: _pages,
|
||||
@@ -91,6 +90,65 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
|
||||
// --- WIDGETS DE CONTEÚDO ---
|
||||
|
||||
// 2. O teu StreamBuilder foi movido para aqui
|
||||
Widget _buildTeamsContent() {
|
||||
return StreamBuilder<List<Map<String, dynamic>>>(
|
||||
stream: _teamController.teamsStream,
|
||||
builder: (context, snapshot) {
|
||||
// Verificar estado de carregamento
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
// Verificar erros ou lista vazia
|
||||
if (snapshot.hasError) {
|
||||
return Center(child: Text("Erro: ${snapshot.error}"));
|
||||
}
|
||||
if (!snapshot.hasData || snapshot.data!.isEmpty) {
|
||||
return const Center(child: Text("Ainda não tens equipas."));
|
||||
}
|
||||
|
||||
// Obter dados (Lista simples do Supabase)
|
||||
final teams = snapshot.data!;
|
||||
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: teams.length,
|
||||
itemBuilder: (context, index) {
|
||||
final team = teams[index];
|
||||
|
||||
// Construção do Card da Equipa
|
||||
return Card(
|
||||
elevation: 2,
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: HomeConfig.primaryColor,
|
||||
child: Text(
|
||||
team['name'][0].toUpperCase(),
|
||||
style: const TextStyle(color: Colors.white),
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
team['name'],
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
subtitle: Text("Época: ${team['season']}"),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.delete, color: Colors.red),
|
||||
onPressed: () {
|
||||
// Confirmação antes de apagar (Opcional, mas recomendado)
|
||||
_teamController.deleteTeam(team['id']);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHomeContent() {
|
||||
return SingleChildScrollView(
|
||||
child: Padding(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:playmaker/pages/home.dart';
|
||||
import 'package:playmaker/controllers/login_controller.dart';
|
||||
import '../widgets/login_widgets.dart';
|
||||
import '../../Controllers/login_controller.dart';
|
||||
import 'home.dart'; // <--- IMPORTANTE: Importa a tua HomeScreen
|
||||
|
||||
class LoginPage extends StatefulWidget {
|
||||
const LoginPage({super.key});
|
||||
@@ -34,9 +34,7 @@ class _LoginPageState extends State<LoginPage> {
|
||||
return Center(
|
||||
child: SingleChildScrollView(
|
||||
child: Container(
|
||||
// AGORA: Ocupa 60% da largura da tela, igual ao Register
|
||||
width: screenWidth * 0.6,
|
||||
// Garante que em telemóveis não fique demasiado apertado
|
||||
constraints: const BoxConstraints(minWidth: 340),
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
@@ -48,13 +46,17 @@ class _LoginPageState extends State<LoginPage> {
|
||||
LoginFormFields(controller: controller),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// AQUI ESTÁ A MUDANÇA PRINCIPAL
|
||||
LoginButton(
|
||||
controller: controller,
|
||||
onLoginSuccess: () {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) => const HomeScreen()),
|
||||
);
|
||||
// Verifica se o widget ainda está no ecrã antes de navegar
|
||||
if (mounted) {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) => const HomeScreen()),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
/*import 'package:flutter/material.dart';
|
||||
import 'package:playmaker/controllers/team_controllers.dart';
|
||||
import '../models/team_model.dart';
|
||||
import '../widgets/team_widgets.dart';
|
||||
@@ -13,7 +12,6 @@ class TeamsPage extends StatelessWidget {
|
||||
final TeamController controller = TeamController();
|
||||
|
||||
return Scaffold(
|
||||
body: StreamBuilder<QuerySnapshot>(
|
||||
stream: controller.teamsStream,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.hasError) return const Center(child: Text('Erro ao carregar'));
|
||||
@@ -57,4 +55,4 @@ class TeamsPage extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
@@ -125,4 +125,7 @@ class TeamStatsPage extends StatelessWidget {
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class StatsController {
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
|
||||
class AuthService {
|
||||
final FirebaseAuth _auth = FirebaseAuth.instance;
|
||||
|
||||
// Retorna o ID do utilizador atual
|
||||
String? get currentUid => _auth.currentUser?.uid;
|
||||
|
||||
// Retorna o email do utilizador (útil para mostrar no perfil)
|
||||
String? get currentUserEmail => _auth.currentUser?.email;
|
||||
|
||||
// Verifica se o utilizador está logado
|
||||
bool get isLoggedIn => _auth.currentUser != null;
|
||||
|
||||
// Função para fazer Logout (Sair)
|
||||
Future<void> signOut() async {
|
||||
await _auth.signOut();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:playmaker/Controllers/login_controller.dart';
|
||||
import 'package:playmaker/controllers/login_controller.dart';
|
||||
import 'package:playmaker/pages/RegisterPage.dart';
|
||||
|
||||
class BasketTrackHeader extends StatelessWidget {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../Controllers/register_controller.dart';
|
||||
import '../controllers/register_controller.dart'; // Garante que o caminho está certo
|
||||
|
||||
class RegisterHeader extends StatelessWidget {
|
||||
const RegisterHeader({super.key});
|
||||
@@ -8,7 +8,6 @@ class RegisterHeader extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
|
||||
// Mesma lógica de tamanhos do Login
|
||||
final logoSize = screenWidth > 600 ? 150.0 : 100.0;
|
||||
final titleFontSize = screenWidth > 600 ? 48.0 : 36.0;
|
||||
final subtitleFontSize = screenWidth > 600 ? 22.0 : 18.0;
|
||||
@@ -46,7 +45,6 @@ class RegisterHeader extends StatelessWidget {
|
||||
|
||||
class RegisterFormFields extends StatefulWidget {
|
||||
final RegisterController controller;
|
||||
|
||||
|
||||
const RegisterFormFields({super.key, required this.controller});
|
||||
|
||||
@@ -60,75 +58,88 @@ class _RegisterFormFieldsState extends State<RegisterFormFields> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
// Padding vertical idêntico ao login
|
||||
final verticalPadding = screenWidth > 600 ? 22.0 : 16.0;
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
TextField(
|
||||
controller: widget.controller.emailController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'E-mail',
|
||||
prefixIcon: const Icon(Icons.email_outlined),
|
||||
// O erro agora vem diretamente do controller
|
||||
errorText: widget.controller.emailError,
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
contentPadding: EdgeInsets.symmetric(vertical: verticalPadding, horizontal: 16),
|
||||
),
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Campo Password
|
||||
TextField(
|
||||
controller: widget.controller.passwordController,
|
||||
obscureText: _obscurePassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Palavra-passe',
|
||||
prefixIcon: const Icon(Icons.lock_outlined),
|
||||
errorText: widget.controller.passwordError,
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_obscurePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined),
|
||||
onPressed: () => setState(() => _obscurePassword = !_obscurePassword),
|
||||
// IMPORTANTE: Envolvemos tudo num Form usando a chave do controller
|
||||
return Form(
|
||||
key: widget.controller.formKey,
|
||||
child: Column(
|
||||
children: [
|
||||
// Campo Nome (Opcional, mas útil)
|
||||
TextFormField(
|
||||
controller: widget.controller.nameController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Nome Completo',
|
||||
prefixIcon: const Icon(Icons.person_outline),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
contentPadding: EdgeInsets.symmetric(vertical: verticalPadding, horizontal: 16),
|
||||
),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
contentPadding: EdgeInsets.symmetric(vertical: verticalPadding, horizontal: 16),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Campo Confirmar Password
|
||||
TextField(
|
||||
controller: widget.controller.confirmPasswordController,
|
||||
obscureText: _obscurePassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Confirmar Palavra-passe',
|
||||
prefixIcon: const Icon(Icons.lock_clock_outlined),
|
||||
errorText: widget.controller.confirmPasswordError,
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
contentPadding: EdgeInsets.symmetric(vertical: verticalPadding, horizontal: 16),
|
||||
// Campo Email
|
||||
TextFormField(
|
||||
controller: widget.controller.emailController,
|
||||
// Validação automática ligada ao controller
|
||||
validator: widget.controller.validateEmail,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'E-mail',
|
||||
prefixIcon: const Icon(Icons.email_outlined),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
contentPadding: EdgeInsets.symmetric(vertical: verticalPadding, horizontal: 16),
|
||||
),
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Campo Password
|
||||
TextFormField(
|
||||
controller: widget.controller.passwordController,
|
||||
obscureText: _obscurePassword,
|
||||
validator: widget.controller.validatePassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Palavra-passe',
|
||||
prefixIcon: const Icon(Icons.lock_outlined),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_obscurePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined),
|
||||
onPressed: () => setState(() => _obscurePassword = !_obscurePassword),
|
||||
),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
contentPadding: EdgeInsets.symmetric(vertical: verticalPadding, horizontal: 16),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Campo Confirmar Password
|
||||
TextFormField(
|
||||
controller: widget.controller.confirmPasswordController,
|
||||
obscureText: _obscurePassword,
|
||||
validator: widget.controller.validateConfirmPassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Confirmar Palavra-passe',
|
||||
prefixIcon: const Icon(Icons.lock_clock_outlined),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
contentPadding: EdgeInsets.symmetric(vertical: verticalPadding, horizontal: 16),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class RegisterButton extends StatelessWidget {
|
||||
final RegisterController controller;
|
||||
final VoidCallback onRegisterSuccess;
|
||||
|
||||
const RegisterButton({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.onRegisterSuccess,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
|
||||
// Mesmos tamanhos exatos do LoginButton
|
||||
final buttonHeight = screenWidth > 600 ? 70.0 : 58.0;
|
||||
final fontSize = screenWidth > 600 ? 22.0 : 18.0;
|
||||
|
||||
@@ -136,12 +147,8 @@ class RegisterButton extends StatelessWidget {
|
||||
width: double.infinity,
|
||||
height: buttonHeight,
|
||||
child: ElevatedButton(
|
||||
onPressed: controller.isLoading ? null : () async {
|
||||
final success = await controller.signUp();
|
||||
if (success) {
|
||||
onRegisterSuccess();
|
||||
}
|
||||
},
|
||||
// Passamos o context para o controller lidar com as SnackBars e Navegação
|
||||
onPressed: controller.isLoading ? null : () => controller.signUp(context),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: const Color(0xFFE74C3C),
|
||||
foregroundColor: Colors.white,
|
||||
|
||||
@@ -14,7 +14,7 @@ class TeamCard extends StatelessWidget {
|
||||
|
||||
});
|
||||
|
||||
@override
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
elevation: 3,
|
||||
|
||||
Reference in New Issue
Block a user