agora as jogadrres vao para o supabase
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import 'package:flutter/material.dart';
|
/*import 'package:flutter/material.dart';
|
||||||
import 'package:supabase_flutter/supabase_flutter.dart';
|
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||||
import '../models/person_model.dart';
|
import '../models/person_model.dart';
|
||||||
|
|
||||||
@@ -155,4 +155,4 @@ class StatsController {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}*/
|
||||||
@@ -247,6 +247,7 @@ class _TeamsPageState extends State<TeamsPage> {
|
|||||||
context: context,
|
context: context,
|
||||||
builder: (context) => CreateTeamDialog(
|
builder: (context) => CreateTeamDialog(
|
||||||
onConfirm: (name, season, imageUrl) => controller.createTeam(name, season, imageUrl),
|
onConfirm: (name, season, imageUrl) => controller.createTeam(name, season, imageUrl),
|
||||||
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:supabase_flutter/supabase_flutter.dart';
|
||||||
import '../models/team_model.dart';
|
import '../models/team_model.dart';
|
||||||
import '../models/person_model.dart';
|
import '../models/person_model.dart';
|
||||||
// Se tiveres os widgets noutro ficheiro, importa-os.
|
|
||||||
// Caso contrário, podes colar as classes StatsHeader, etc. no fundo deste ficheiro.
|
|
||||||
import '../widgets/team_widgets.dart';
|
import '../widgets/team_widgets.dart';
|
||||||
import '../widgets/stats_widgets.dart'; // Assumindo que criaste este ficheiro anteriormente
|
import '../widgets/stats_widgets.dart';
|
||||||
|
|
||||||
class TeamStatsPage extends StatefulWidget {
|
class TeamStatsPage extends StatefulWidget {
|
||||||
final Team team;
|
final Team team;
|
||||||
@@ -17,74 +16,77 @@ class TeamStatsPage extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _TeamStatsPageState extends State<TeamStatsPage> {
|
class _TeamStatsPageState extends State<TeamStatsPage> {
|
||||||
// Instancia o controlador local
|
|
||||||
final StatsController _controller = StatsController();
|
final StatsController _controller = StatsController();
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_controller.dispose();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
backgroundColor: const Color(0xFFF5F7FA),
|
backgroundColor: const Color(0xFFF5F7FA),
|
||||||
body: Column(
|
body: Column(
|
||||||
children: [
|
children: [
|
||||||
// Header (Widget que criámos antes)
|
// Cabeçalho com informações da equipa
|
||||||
StatsHeader(team: widget.team),
|
StatsHeader(team: widget.team),
|
||||||
|
|
||||||
Expanded(
|
Expanded(
|
||||||
child: StreamBuilder<List<Person>>(
|
child: StreamBuilder<List<Person>>(
|
||||||
// LÊ DA LISTA LOCAL
|
// O StreamBuilder reconstrói a UI automaticamente sempre que o Supabase envia novos dados
|
||||||
stream: _controller.getMembers(widget.team.id),
|
stream: _controller.getMembers(widget.team.id),
|
||||||
builder: (context, snapshot) {
|
builder: (context, snapshot) {
|
||||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||||
return const Center(child: CircularProgressIndicator());
|
return const Center(child: CircularProgressIndicator());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (snapshot.hasError) {
|
||||||
|
return Center(child: Text("Erro ao carregar: ${snapshot.error}"));
|
||||||
|
}
|
||||||
|
|
||||||
final members = snapshot.data ?? [];
|
final members = snapshot.data ?? [];
|
||||||
|
|
||||||
|
// Filtros para organizar a lista
|
||||||
final coaches = members.where((m) => m.type == 'Treinador').toList();
|
final coaches = members.where((m) => m.type == 'Treinador').toList();
|
||||||
final players = members.where((m) => m.type == 'Jogador').toList();
|
final players = members.where((m) => m.type == 'Jogador').toList();
|
||||||
|
|
||||||
return SingleChildScrollView(
|
return RefreshIndicator(
|
||||||
padding: const EdgeInsets.all(16.0),
|
onRefresh: () async => setState(() {}), // Pull to refresh como backup
|
||||||
child: Column(
|
child: SingleChildScrollView(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
children: [
|
padding: const EdgeInsets.all(16.0),
|
||||||
// Resumo
|
child: Column(
|
||||||
StatsSummaryCard(total: members.length),
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
const SizedBox(height: 30),
|
children: [
|
||||||
|
StatsSummaryCard(total: members.length),
|
||||||
// Secção Treinadores
|
|
||||||
if (coaches.isNotEmpty) ...[
|
|
||||||
const StatsSectionTitle(title: "Treinadores"),
|
|
||||||
...coaches.map((c) => PersonCard(
|
|
||||||
person: c,
|
|
||||||
isCoach: true,
|
|
||||||
onEdit: () => _controller.showEditPersonDialog(context, widget.team.id, c),
|
|
||||||
onDelete: () => _confirmDelete(context, c),
|
|
||||||
)),
|
|
||||||
const SizedBox(height: 30),
|
const SizedBox(height: 30),
|
||||||
],
|
|
||||||
|
|
||||||
// Secção Jogadores
|
// SECÇÃO TREINADORES
|
||||||
const StatsSectionTitle(title: "Jogadores"),
|
if (coaches.isNotEmpty) ...[
|
||||||
if (players.isEmpty)
|
const StatsSectionTitle(title: "Treinadores"),
|
||||||
const Padding(
|
...coaches.map((c) => PersonCard(
|
||||||
padding: EdgeInsets.only(top: 20),
|
person: c,
|
||||||
child: Text("Nenhum jogador adicionado.", style: TextStyle(color: Colors.grey)),
|
isCoach: true,
|
||||||
)
|
onEdit: () => _controller.showEditPersonDialog(context, widget.team.id, c),
|
||||||
else
|
onDelete: () => _confirmDelete(context, c),
|
||||||
...players.map((p) => PersonCard(
|
)),
|
||||||
person: p,
|
const SizedBox(height: 30),
|
||||||
isCoach: false,
|
],
|
||||||
onEdit: () => _controller.showEditPersonDialog(context, widget.team.id, p),
|
|
||||||
onDelete: () => _confirmDelete(context, p),
|
// SECÇÃO JOGADORES
|
||||||
)),
|
const StatsSectionTitle(title: "Jogadores"),
|
||||||
const SizedBox(height: 80),
|
if (players.isEmpty)
|
||||||
],
|
const Padding(
|
||||||
|
padding: EdgeInsets.only(top: 20),
|
||||||
|
child: Text("Nenhum jogador nesta equipa.",
|
||||||
|
style: TextStyle(color: Colors.grey, fontSize: 16)),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
...players.map((p) => PersonCard(
|
||||||
|
person: p,
|
||||||
|
isCoach: false,
|
||||||
|
onEdit: () => _controller.showEditPersonDialog(context, widget.team.id, p),
|
||||||
|
onDelete: () => _confirmDelete(context, p),
|
||||||
|
)),
|
||||||
|
const SizedBox(height: 80), // Espaço para o FAB não tapar o último card
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -93,7 +95,8 @@ class _TeamStatsPageState extends State<TeamStatsPage> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
floatingActionButton: FloatingActionButton(
|
floatingActionButton: FloatingActionButton(
|
||||||
heroTag: 'player_fab',
|
// Hero tag única para evitar o erro de tags duplicadas
|
||||||
|
heroTag: 'fab_team_${widget.team.id}',
|
||||||
onPressed: () => _controller.showAddPersonDialog(context, widget.team.id),
|
onPressed: () => _controller.showAddPersonDialog(context, widget.team.id),
|
||||||
backgroundColor: const Color(0xFF00C853),
|
backgroundColor: const Color(0xFF00C853),
|
||||||
child: const Icon(Icons.add, color: Colors.white),
|
child: const Icon(Icons.add, color: Colors.white),
|
||||||
@@ -104,15 +107,15 @@ class _TeamStatsPageState extends State<TeamStatsPage> {
|
|||||||
void _confirmDelete(BuildContext context, Person person) {
|
void _confirmDelete(BuildContext context, Person person) {
|
||||||
showDialog(
|
showDialog(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (context) => AlertDialog(
|
builder: (ctx) => AlertDialog(
|
||||||
title: const Text("Eliminar?"),
|
title: const Text("Eliminar Membro?"),
|
||||||
content: Text("Remover ${person.name}?"),
|
content: Text("Tens a certeza que queres remover ${person.name}?"),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text("Cancelar")),
|
TextButton(onPressed: () => Navigator.pop(ctx), child: const Text("Cancelar")),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: () {
|
onPressed: () async {
|
||||||
_controller.deletePerson(widget.team.id, person.id);
|
await _controller.deletePerson(person.id);
|
||||||
Navigator.pop(context);
|
if (ctx.mounted) Navigator.pop(ctx);
|
||||||
},
|
},
|
||||||
child: const Text("Eliminar", style: TextStyle(color: Colors.red)),
|
child: const Text("Eliminar", style: TextStyle(color: Colors.red)),
|
||||||
),
|
),
|
||||||
@@ -122,42 +125,28 @@ class _TeamStatsPageState extends State<TeamStatsPage> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- CONTROLLER LOCAL (SEM SUPABASE) ---
|
// --- CONTROLLER SUPABASE ---
|
||||||
|
|
||||||
class StatsController {
|
class StatsController {
|
||||||
// Base de dados simulada na memória (Estática para não perder dados ao mudar de ecrã)
|
final _supabase = Supabase.instance.client;
|
||||||
static final List<Map<String, dynamic>> _mockMembers = [
|
|
||||||
// Podes deixar vazio ou meter dados de teste
|
|
||||||
// {'id': '1', 'team_id': 'exemplo', 'name': 'Mourinho', 'type': 'Treinador', 'number': null},
|
|
||||||
];
|
|
||||||
|
|
||||||
// Stream para atualizar a UI automaticamente
|
// 1. LER (A escuta em tempo real)
|
||||||
final StreamController<List<Person>> _streamController = StreamController<List<Person>>.broadcast();
|
|
||||||
|
|
||||||
// 1. LER (Filtra a lista local)
|
|
||||||
Stream<List<Person>> getMembers(String teamId) {
|
Stream<List<Person>> getMembers(String teamId) {
|
||||||
// Pequeno delay para garantir que o Stream ouve a primeira emissão
|
return _supabase
|
||||||
Future.delayed(Duration.zero, () => _emitMembers(teamId));
|
.from('members')
|
||||||
return _streamController.stream;
|
.stream(primaryKey: ['id']) // Garante que a PK na tabela é 'id'
|
||||||
|
.eq('team_id', teamId)
|
||||||
|
.order('name', ascending: true)
|
||||||
|
.map((data) => data.map((json) => Person.fromMap(json)).toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Função auxiliar para atualizar quem está a ouvir
|
// 2. APAGAR
|
||||||
void _emitMembers(String teamId) {
|
Future<void> deletePerson(String personId) async {
|
||||||
final filtered = _mockMembers
|
try {
|
||||||
.where((m) => m['team_id'] == teamId)
|
await _supabase.from('members').delete().eq('id', personId);
|
||||||
.map((m) => Person.fromMap(m))
|
} catch (e) {
|
||||||
.toList();
|
debugPrint("Erro ao eliminar: $e");
|
||||||
|
}
|
||||||
// Ordenar por nome
|
|
||||||
filtered.sort((a, b) => a.name.compareTo(b.name));
|
|
||||||
|
|
||||||
_streamController.add(filtered);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. APAGAR LOCALMENTE
|
|
||||||
void deletePerson(String teamId, String personId) {
|
|
||||||
_mockMembers.removeWhere((m) => m['id'] == personId);
|
|
||||||
_emitMembers(teamId); // Atualiza o ecrã
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. DIÁLOGOS
|
// 3. DIÁLOGOS
|
||||||
@@ -179,33 +168,38 @@ class StatsController {
|
|||||||
context: context,
|
context: context,
|
||||||
builder: (ctx) => StatefulBuilder(
|
builder: (ctx) => StatefulBuilder(
|
||||||
builder: (ctx, setState) => AlertDialog(
|
builder: (ctx, setState) => AlertDialog(
|
||||||
title: Text(isEdit ? "Editar" : "Adicionar"),
|
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
|
||||||
content: Column(
|
title: Text(isEdit ? "Editar Membro" : "Novo Membro"),
|
||||||
mainAxisSize: MainAxisSize.min,
|
content: SingleChildScrollView(
|
||||||
children: [
|
child: Column(
|
||||||
TextField(
|
mainAxisSize: MainAxisSize.min,
|
||||||
controller: nameCtrl,
|
children: [
|
||||||
decoration: const InputDecoration(labelText: "Nome"),
|
|
||||||
textCapitalization: TextCapitalization.sentences,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 10),
|
|
||||||
DropdownButtonFormField<String>(
|
|
||||||
value: selectedType,
|
|
||||||
decoration: const InputDecoration(labelText: "Função"),
|
|
||||||
items: ["Jogador", "Treinador"].map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(),
|
|
||||||
onChanged: (v) {
|
|
||||||
if (v != null) setState(() => selectedType = v);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
if (selectedType == "Jogador") ...[
|
|
||||||
const SizedBox(height: 10),
|
|
||||||
TextField(
|
TextField(
|
||||||
controller: numCtrl,
|
controller: nameCtrl,
|
||||||
decoration: const InputDecoration(labelText: "Número da Camisola"),
|
decoration: const InputDecoration(labelText: "Nome Completo"),
|
||||||
keyboardType: TextInputType.text,
|
textCapitalization: TextCapitalization.words,
|
||||||
),
|
),
|
||||||
]
|
const SizedBox(height: 15),
|
||||||
],
|
DropdownButtonFormField<String>(
|
||||||
|
value: selectedType,
|
||||||
|
decoration: const InputDecoration(labelText: "Função"),
|
||||||
|
items: ["Jogador", "Treinador"]
|
||||||
|
.map((e) => DropdownMenuItem(value: e, child: Text(e)))
|
||||||
|
.toList(),
|
||||||
|
onChanged: (v) {
|
||||||
|
if (v != null) setState(() => selectedType = v);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
if (selectedType == "Jogador") ...[
|
||||||
|
const SizedBox(height: 15),
|
||||||
|
TextField(
|
||||||
|
controller: numCtrl,
|
||||||
|
decoration: const InputDecoration(labelText: "Número da Camisola"),
|
||||||
|
keyboardType: TextInputType.number,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
@@ -213,40 +207,41 @@ class StatsController {
|
|||||||
child: const Text("Cancelar")
|
child: const Text("Cancelar")
|
||||||
),
|
),
|
||||||
ElevatedButton(
|
ElevatedButton(
|
||||||
style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF00C853)),
|
style: ElevatedButton.styleFrom(
|
||||||
onPressed: () {
|
backgroundColor: const Color(0xFF00C853),
|
||||||
|
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))
|
||||||
|
),
|
||||||
|
onPressed: () async {
|
||||||
if (nameCtrl.text.trim().isEmpty) return;
|
if (nameCtrl.text.trim().isEmpty) return;
|
||||||
|
|
||||||
String? numeroFinal = (selectedType == "Treinador")
|
String? numeroFinal = (selectedType == "Treinador")
|
||||||
? null
|
? null
|
||||||
: (numCtrl.text.trim().isEmpty ? null : numCtrl.text.trim());
|
: (numCtrl.text.trim().isEmpty ? null : numCtrl.text.trim());
|
||||||
|
|
||||||
if (isEdit) {
|
try {
|
||||||
// ATUALIZAR NA LISTA LOCAL
|
if (isEdit) {
|
||||||
final index = _mockMembers.indexWhere((m) => m['id'] == person!.id);
|
await _supabase.from('members').update({
|
||||||
if (index != -1) {
|
'name': nameCtrl.text.trim(),
|
||||||
_mockMembers[index] = {
|
'type': selectedType,
|
||||||
'id': person!.id,
|
'number': numeroFinal,
|
||||||
|
}).eq('id', person.id);
|
||||||
|
} else {
|
||||||
|
await _supabase.from('members').insert({
|
||||||
'team_id': teamId,
|
'team_id': teamId,
|
||||||
'name': nameCtrl.text.trim(),
|
'name': nameCtrl.text.trim(),
|
||||||
'type': selectedType,
|
'type': selectedType,
|
||||||
'number': numeroFinal,
|
'number': numeroFinal,
|
||||||
};
|
});
|
||||||
|
}
|
||||||
|
if (ctx.mounted) Navigator.pop(ctx);
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint("Erro Supabase: $e");
|
||||||
|
if (ctx.mounted) {
|
||||||
|
ScaffoldMessenger.of(ctx).showSnackBar(
|
||||||
|
SnackBar(content: Text("Erro ao guardar: $e"), backgroundColor: Colors.red)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
// CRIAR NA LISTA LOCAL (Gera ID com a data atual)
|
|
||||||
_mockMembers.add({
|
|
||||||
'id': DateTime.now().millisecondsSinceEpoch.toString(),
|
|
||||||
'team_id': teamId,
|
|
||||||
'name': nameCtrl.text.trim(),
|
|
||||||
'type': selectedType,
|
|
||||||
'number': numeroFinal,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Atualiza a UI
|
|
||||||
_emitMembers(teamId);
|
|
||||||
Navigator.pop(ctx);
|
|
||||||
},
|
},
|
||||||
child: const Text("Guardar", style: TextStyle(color: Colors.white)),
|
child: const Text("Guardar", style: TextStyle(color: Colors.white)),
|
||||||
)
|
)
|
||||||
@@ -256,7 +251,5 @@ class StatsController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void dispose() {
|
void dispose() {}
|
||||||
_streamController.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user