80 lines
2.5 KiB
Dart
80 lines
2.5 KiB
Dart
import 'dart:async';
|
|
|
|
class TeamController {
|
|
// --- BASE DE DADOS LOCAL (Listas Estáticas) ---
|
|
// Mantemos estático para que os dados persistam entre navegações de ecrãs
|
|
static final List<Map<String, dynamic>> _teams = [];
|
|
static final List<Map<String, dynamic>> _members = [];
|
|
|
|
static List<Map<String, dynamic>> get members => _members;
|
|
|
|
// StreamController broadcast para permitir múltiplos ouvintes (ex: Home e TeamsPage)
|
|
final _streamController = StreamController<List<Map<String, dynamic>>>.broadcast();
|
|
|
|
// 1. STREAM
|
|
// Retorna a lista atual mal alguém subscreve
|
|
Stream<List<Map<String, dynamic>>> get teamsStream {
|
|
_notifyListeners();
|
|
return _streamController.stream;
|
|
}
|
|
|
|
// 2. CRIAR
|
|
Future<void> createTeam(String name, String season, String imageUrl) async {
|
|
await Future.delayed(const Duration(milliseconds: 100)); // Simula latência
|
|
final newTeam = {
|
|
'id': DateTime.now().millisecondsSinceEpoch.toString(),
|
|
'name': name,
|
|
'season': season,
|
|
'image_url': imageUrl,
|
|
'is_favorite': false, // Inicializa sempre como falso
|
|
};
|
|
_teams.add(newTeam);
|
|
_notifyListeners();
|
|
}
|
|
|
|
// 3. ELIMINAR
|
|
Future<void> deleteTeam(String id) async {
|
|
_teams.removeWhere((team) => team['id'] == id);
|
|
_members.removeWhere((member) => member['team_id'] == id);
|
|
_notifyListeners();
|
|
}
|
|
|
|
// 4. FAVORITAR
|
|
Future<void> toggleFavorite(String teamId) async {
|
|
final index = _teams.indexWhere((t) => t['id'] == teamId);
|
|
if (index != -1) {
|
|
// Inverte o valor booleano (trata null como false)
|
|
final bool currentStatus = _teams[index]['is_favorite'] ?? false;
|
|
_teams[index]['is_favorite'] = !currentStatus;
|
|
_notifyListeners();
|
|
}
|
|
}
|
|
|
|
// 5. CONTAR JOGADORES
|
|
Future<int> getPlayerCount(String teamId) async {
|
|
return _members.where((m) => m['team_id'] == teamId).length;
|
|
}
|
|
|
|
// 6. NOTIFICAR E ORDENAR (Única versão corrigida)
|
|
void _notifyListeners() {
|
|
if (_streamController.isClosed) return;
|
|
|
|
// Ordenação: 1º Favoritos, 2º Nome (Alfabético)
|
|
_teams.sort((a, b) {
|
|
final bool favA = a['is_favorite'] ?? false;
|
|
final bool favB = b['is_favorite'] ?? false;
|
|
|
|
if (favA == favB) {
|
|
return (a['name'] as String).compareTo(b['name'] as String);
|
|
}
|
|
return favB ? 1 : -1; // b (favorito) vem antes de a
|
|
});
|
|
|
|
// Enviamos uma CÓPIA da lista (List.from) para garantir que o StreamBuilder detecte a mudança
|
|
_streamController.add(List.from(_teams));
|
|
}
|
|
|
|
void dispose() {
|
|
_streamController.close();
|
|
}
|
|
} |