fazer vitoria e derrota

This commit is contained in:
2026-03-10 17:15:10 +00:00
parent d720e09866
commit 49bb371ef4
12 changed files with 940 additions and 742 deletions

View File

@@ -9,7 +9,7 @@ android {
namespace = "com.example.playmaker" namespace = "com.example.playmaker"
compileSdk = flutter.compileSdkVersion compileSdk = flutter.compileSdkVersion
//ndkVersion = flutter.ndkVersion //ndkVersion = flutter.ndkVersion
ndkVersion = "26.1.10909125" ndkVersion = "27.0.12077973"
compileOptions { compileOptions {
sourceCompatibility = JavaVersion.VERSION_11 sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11

View File

@@ -116,6 +116,7 @@ class PlacarController {
"pts": s['pts'] ?? 0, "rbs": s['rbs'] ?? 0, "ast": s['ast'] ?? 0, "pts": s['pts'] ?? 0, "rbs": s['rbs'] ?? 0, "ast": s['ast'] ?? 0,
"stl": s['stl'] ?? 0, "tov": s['tov'] ?? 0, "blk": s['blk'] ?? 0, "stl": s['stl'] ?? 0, "tov": s['tov'] ?? 0, "blk": s['blk'] ?? 0,
"fls": s['fls'] ?? 0, "fgm": s['fgm'] ?? 0, "fga": s['fga'] ?? 0, "fls": s['fls'] ?? 0, "fgm": s['fgm'] ?? 0, "fga": s['fga'] ?? 0,
"ftm": s['ftm'] ?? 0, "fta": s['fta'] ?? 0, "orb": s['orb'] ?? 0, "drb": s['drb'] ?? 0, // <-- VARIÁVEIS NOVAS AQUI!
}; };
myFouls += (s['fls'] as int? ?? 0); myFouls += (s['fls'] as int? ?? 0);
} }
@@ -135,6 +136,7 @@ class PlacarController {
"pts": s['pts'] ?? 0, "rbs": s['rbs'] ?? 0, "ast": s['ast'] ?? 0, "pts": s['pts'] ?? 0, "rbs": s['rbs'] ?? 0, "ast": s['ast'] ?? 0,
"stl": s['stl'] ?? 0, "tov": s['tov'] ?? 0, "blk": s['blk'] ?? 0, "stl": s['stl'] ?? 0, "tov": s['tov'] ?? 0, "blk": s['blk'] ?? 0,
"fls": s['fls'] ?? 0, "fgm": s['fgm'] ?? 0, "fga": s['fga'] ?? 0, "fls": s['fls'] ?? 0, "fgm": s['fgm'] ?? 0, "fga": s['fga'] ?? 0,
"ftm": s['ftm'] ?? 0, "fta": s['fta'] ?? 0, "orb": s['orb'] ?? 0, "drb": s['drb'] ?? 0, // <-- VARIÁVEIS NOVAS AQUI!
}; };
opponentFouls += (s['fls'] as int? ?? 0); opponentFouls += (s['fls'] as int? ?? 0);
} }
@@ -156,7 +158,12 @@ class PlacarController {
if (playerNumbers.containsKey(name)) name = "$name (Opp)"; if (playerNumbers.containsKey(name)) name = "$name (Opp)";
playerNumbers[name] = number; playerNumbers[name] = number;
if (dbId != null) playerDbIds[name] = dbId; if (dbId != null) playerDbIds[name] = dbId;
playerStats[name] = {"pts": 0, "rbs": 0, "ast": 0, "stl": 0, "tov": 0, "blk": 0, "fls": 0, "fgm": 0, "fga": 0};
// 👇 ADICIONEI AS 4 VARIÁVEIS NOVAS AQUI!
playerStats[name] = {
"pts": 0, "rbs": 0, "ast": 0, "stl": 0, "tov": 0, "blk": 0,
"fls": 0, "fgm": 0, "fga": 0, "ftm": 0, "fta": 0, "orb": 0, "drb": 0
};
if (isMyTeam) { if (isMyTeam) {
if (isCourt) myCourt.add(name); else myBench.add(name); if (isCourt) myCourt.add(name); else myBench.add(name);
@@ -182,12 +189,15 @@ class PlacarController {
} else { } else {
timer.cancel(); timer.cancel();
isRunning = false; isRunning = false;
if (currentQuarter < 4) { if (currentQuarter < 4) {
currentQuarter++; currentQuarter++;
duration = const Duration(minutes: 10); duration = const Duration(minutes: 10);
myFouls = 0; myFouls = 0;
opponentFouls = 0; opponentFouls = 0;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Período $currentQuarter iniciado. Faltas resetadas!'), backgroundColor: Colors.blue)); // 👇 ESTAS DUAS LINHAS ZERAM OS TIMEOUTS NO NOVO PERÍODO
myTimeoutsUsed = 0;
opponentTimeoutsUsed = 0;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Período $currentQuarter iniciado. Faltas e Timeouts resetados!'), backgroundColor: Colors.blue));
} else { } else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('FIM DO JOGO!'), backgroundColor: Colors.red)); ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('FIM DO JOGO!'), backgroundColor: Colors.red));
} }
@@ -256,27 +266,24 @@ class PlacarController {
onUpdate(); onUpdate();
} }
// AGORA RECEBE CONTEXT E SIZE PARA A MATEMÁTICA
void registerShotLocation(BuildContext context, Offset position, Size size) { void registerShotLocation(BuildContext context, Offset position, Size size) {
if (pendingAction == null || pendingPlayer == null) return; if (pendingAction == null || pendingPlayer == null) return;
bool is3Pt = pendingAction!.contains("_3"); bool is3Pt = pendingAction!.contains("_3");
bool is2Pt = pendingAction!.contains("_2"); bool is2Pt = pendingAction!.contains("_2");
// Validação
if (is3Pt || is2Pt) { if (is3Pt || is2Pt) {
bool isValid = _validateShotZone(position, size, is3Pt); bool isValid = _validateShotZone(position, size, is3Pt);
if (!isValid) { if (!isValid) {
// Se a validação falhar, fudeo. Bloqueia.
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar( const SnackBar(
content: Text('🛑 Vai dar merda! Local de lançamento incompatível com a pontuação.'), content: Text('🛑Local de lançamento incompatível com a pontuação.'),
backgroundColor: Colors.red, backgroundColor: Colors.red,
duration: Duration(seconds: 2), duration: Duration(seconds: 2),
) )
); );
return; // Aborta! return;
} }
} }
@@ -290,22 +297,17 @@ class PlacarController {
onUpdate(); onUpdate();
} }
// A MATEMÁTICA DA ZONA
bool _validateShotZone(Offset pos, Size size, bool is3Pt) { bool _validateShotZone(Offset pos, Size size, bool is3Pt) {
double w = size.width; double w = size.width;
double h = size.height; double h = size.height;
// Ajusta o 0.12 e 0.88 se os teus cestos na imagem estiverem mais para o lado
Offset leftHoop = Offset(w * 0.12, h * 0.5); Offset leftHoop = Offset(w * 0.12, h * 0.5);
Offset rightHoop = Offset(w * 0.88, h * 0.5); Offset rightHoop = Offset(w * 0.88, h * 0.5);
// O raio da linha de 3 pontos (Brinca com este 0.28 se a área ficar muito grande ou pequena)
double threePointRadius = w * 0.28; double threePointRadius = w * 0.28;
Offset activeHoop = pos.dx < w / 2 ? leftHoop : rightHoop; Offset activeHoop = pos.dx < w / 2 ? leftHoop : rightHoop;
double distanceToHoop = (pos - activeHoop).distance; double distanceToHoop = (pos - activeHoop).distance;
// Zonas de canto (onde a linha de 3 é reta)
bool isCorner3 = (pos.dy < h * 0.15 || pos.dy > h * 0.85) && bool isCorner3 = (pos.dy < h * 0.15 || pos.dy > h * 0.85) &&
(pos.dx < w * 0.20 || pos.dx > w * 0.80); (pos.dx < w * 0.20 || pos.dx > w * 0.80);
@@ -333,6 +335,7 @@ class PlacarController {
if (isOpponent) opponentScore += pts; else myScore += pts; if (isOpponent) opponentScore += pts; else myScore += pts;
stats["pts"] = stats["pts"]! + pts; stats["pts"] = stats["pts"]! + pts;
if (pts == 2 || pts == 3) { stats["fgm"] = stats["fgm"]! + 1; stats["fga"] = stats["fga"]! + 1; } if (pts == 2 || pts == 3) { stats["fgm"] = stats["fgm"]! + 1; stats["fga"] = stats["fga"]! + 1; }
if (pts == 1) { stats["ftm"] = stats["ftm"]! + 1; stats["fta"] = stats["fta"]! + 1; } // ADICIONADO LANCE LIVRE (FTM/FTA)
} }
else if (action.startsWith("sub_pts_")) { else if (action.startsWith("sub_pts_")) {
int pts = int.parse(action.split("_").last); int pts = int.parse(action.split("_").last);
@@ -343,9 +346,15 @@ class PlacarController {
if (stats["fgm"]! > 0) stats["fgm"] = stats["fgm"]! - 1; if (stats["fgm"]! > 0) stats["fgm"] = stats["fgm"]! - 1;
if (stats["fga"]! > 0) stats["fga"] = stats["fga"]! - 1; if (stats["fga"]! > 0) stats["fga"] = stats["fga"]! - 1;
} }
if (pts == 1) { // ADICIONADO SUBTRAÇÃO LANCE LIVRE
if (stats["ftm"]! > 0) stats["ftm"] = stats["ftm"]! - 1;
if (stats["fta"]! > 0) stats["fta"] = stats["fta"]! - 1;
}
} }
else if (action == "miss_1") { stats["fta"] = stats["fta"]! + 1; } // ADICIONADO BOTAO M1
else if (action == "miss_2" || action == "miss_3") { stats["fga"] = stats["fga"]! + 1; } else if (action == "miss_2" || action == "miss_3") { stats["fga"] = stats["fga"]! + 1; }
else if (action == "add_rbs") { stats["rbs"] = stats["rbs"]! + 1; } else if (action == "add_orb") { stats["orb"] = stats["orb"]! + 1; stats["rbs"] = stats["rbs"]! + 1; } // SEPARAÇÃO ORB
else if (action == "add_drb") { stats["drb"] = stats["drb"]! + 1; stats["rbs"] = stats["rbs"]! + 1; } // SEPARAÇÃO DRB
else if (action == "add_ast") { stats["ast"] = stats["ast"]! + 1; } else if (action == "add_ast") { stats["ast"] = stats["ast"]! + 1; }
else if (action == "add_stl") { stats["stl"] = stats["stl"]! + 1; } else if (action == "add_stl") { stats["stl"] = stats["stl"]! + 1; }
else if (action == "add_tov") { stats["tov"] = stats["tov"]! + 1; } else if (action == "add_tov") { stats["tov"] = stats["tov"]! + 1; }
@@ -399,6 +408,10 @@ class PlacarController {
'fls': stats['fls'], 'fls': stats['fls'],
'fgm': stats['fgm'], 'fgm': stats['fgm'],
'fga': stats['fga'], 'fga': stats['fga'],
'ftm': stats['ftm'], // <-- GRAVAR NA BD
'fta': stats['fta'], // <-- GRAVAR NA BD
'orb': stats['orb'], // <-- GRAVAR NA BD
'drb': stats['drb'], // <-- GRAVAR NA BD
}); });
} }
}); });

View File

@@ -1,8 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:playmaker/grafico%20de%20pizza/widgets/grafico_widgets.dart'; import 'package:playmaker/grafico%20de%20pizza/widgets/grafico_widgets.dart'; // Assume que o PieChartWidget está aqui
import 'dados_grafico.dart'; import 'dados_grafico.dart';
import 'controllers/contollers_grafico.dart'; import 'controllers/contollers_grafico.dart';
import 'package:playmaker/classe/home.config.dart';
class PieChartCard extends StatefulWidget { class PieChartCard extends StatefulWidget {
final PieChartController? controller; final PieChartController? controller;
@@ -11,12 +10,21 @@ class PieChartCard extends StatefulWidget {
final Color backgroundColor; final Color backgroundColor;
final VoidCallback? onTap; final VoidCallback? onTap;
// Variáveis de escala e tamanho
final double sf;
final double cardWidth;
final double cardHeight;
const PieChartCard({ const PieChartCard({
super.key, super.key,
this.controller, this.controller,
this.title = 'DESEMPENHO', this.title = 'DESEMPENHO',
this.subtitle = 'Vitórias vs Derrotas', this.subtitle = 'Vitórias vs Derrotas',
this.onTap, required this.backgroundColor, this.onTap,
required this.backgroundColor,
this.sf = 1.0,
required this.cardWidth,
required this.cardHeight,
}); });
@override @override
@@ -57,6 +65,7 @@ class _PieChartCardState extends State<PieChartCard> with SingleTickerProviderSt
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final data = _controller.chartData; final data = _controller.chartData;
final double sf = widget.sf;
return AnimatedBuilder( return AnimatedBuilder(
animation: _animation, animation: _animation,
@@ -69,20 +78,20 @@ class _PieChartCardState extends State<PieChartCard> with SingleTickerProviderSt
), ),
); );
}, },
child: Container( child: SizedBox( // <-- Força a largura e altura exatas passadas pelo HomeScreen
width: HomeConfig.cardwidthPadding, width: widget.cardWidth,
height: HomeConfig.cardheightPadding, height: widget.cardHeight,
child: Card( child: Card(
elevation: 0, elevation: 0,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20 * sf),
), ),
child: InkWell( child: InkWell(
onTap: widget.onTap, onTap: widget.onTap,
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20 * sf),
child: Container( child: Container(
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20 * sf),
gradient: LinearGradient( gradient: LinearGradient(
begin: Alignment.topLeft, begin: Alignment.topLeft,
end: Alignment.bottomRight, end: Alignment.bottomRight,
@@ -93,55 +102,60 @@ class _PieChartCardState extends State<PieChartCard> with SingleTickerProviderSt
), ),
), ),
child: Padding( child: Padding(
padding: const EdgeInsets.all(20.0), padding: EdgeInsets.all(16.0 * sf),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// Cabeçalho compacto // Cabeçalho compacto
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Column( Expanded(
crossAxisAlignment: CrossAxisAlignment.start, child: Column(
children: [ crossAxisAlignment: CrossAxisAlignment.start,
Text( children: [
widget.title, Text(
style: TextStyle( widget.title,
fontSize: 14, // Pequeno style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 12 * sf,
color: Colors.white.withOpacity(0.9), fontWeight: FontWeight.bold,
letterSpacing: 1.5, color: Colors.white.withOpacity(0.9),
letterSpacing: 1.5,
),
), ),
), SizedBox(height: 2 * sf),
SizedBox(height: 2), // Muito pequeno Text(
Text( widget.subtitle,
widget.subtitle, style: TextStyle(
style: TextStyle( fontSize: 14 * sf,
fontSize: 16, // Moderado fontWeight: FontWeight.bold,
fontWeight: FontWeight.bold, color: Colors.white,
color: Colors.white, ),
maxLines: 1,
overflow: TextOverflow.ellipsis,
), ),
), ],
], ),
), ),
Container( Container(
padding: EdgeInsets.all(6), // Pequeno padding: EdgeInsets.all(6 * sf),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.orange.withOpacity(0.8), color: Colors.orange.withOpacity(0.8),
shape: BoxShape.circle, shape: BoxShape.circle,
), ),
child: Icon( child: Icon(
Icons.pie_chart, Icons.pie_chart,
size: 18, // Pequeno size: 16 * sf,
color: Colors.white, color: Colors.white,
), ),
), ),
], ],
), ),
SizedBox(height: 8), // Pequeno espaço SizedBox(height: 8 * sf),
// Conteúdo principal - COMPACTO E CONTROLADO // Conteúdo principal
Expanded( Expanded(
child: Row( child: Row(
children: [ children: [
@@ -153,205 +167,26 @@ class _PieChartCardState extends State<PieChartCard> with SingleTickerProviderSt
victoryPercentage: data.victoryPercentage, victoryPercentage: data.victoryPercentage,
defeatPercentage: data.defeatPercentage, defeatPercentage: data.defeatPercentage,
drawPercentage: data.drawPercentage, drawPercentage: data.drawPercentage,
size: 130, // Pequeno para caber size: 120, // O PieChartWidget vai multiplicar isto por `sf` internamente
sf: sf, // <-- Passa a escala para o gráfico
), ),
), ),
), ),
SizedBox(width: 8), // Pequeno espaço SizedBox(width: 8 * sf),
// Estatísticas - EXTREMAMENTE COMPACTAS // Estatísticas ultra compactas e sem overflows
Expanded( Expanded(
flex: 2, flex: 2,
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// Vitórias - Layout horizontal ultra compacto _buildMiniStatRow("VIT", data.victories.toString(), (data.victoryPercentage * 100).toStringAsFixed(0), Colors.green, sf),
Container( _buildDivider(sf),
margin: EdgeInsets.only(bottom: 6), // Muito pequeno _buildMiniStatRow("DER", data.defeats.toString(), (data.defeatPercentage * 100).toStringAsFixed(0), Colors.red, sf),
child: Row( _buildDivider(sf),
crossAxisAlignment: CrossAxisAlignment.center, _buildMiniStatRow("TOT", data.total.toString(), "100", Colors.white, sf),
children: [
// Número
Text(
data.victories.toString(),
style: TextStyle(
fontSize: 26, // Pequeno mas legível
fontWeight: FontWeight.bold,
color: Colors.green,
height: 0.8,
),
),
SizedBox(width: 6), // Pequeno
// Info compacta
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Container(
width: 8,
height: 8,
margin: EdgeInsets.only(right: 4),
decoration: BoxDecoration(
color: Colors.green,
shape: BoxShape.circle,
),
),
Text(
'VIT',
style: TextStyle(
fontSize: 10, // Muito pequeno
color: Colors.white.withOpacity(0.8),
fontWeight: FontWeight.w600,
),
),
],
),
SizedBox(height: 2),
Text(
'${(data.victoryPercentage * 100).toStringAsFixed(0)}%',
style: TextStyle(
fontSize: 12, // Pequeno
color: Colors.green,
fontWeight: FontWeight.bold,
),
),
],
),
),
],
),
),
// Divisor sutil
Container(
height: 0.5,
color: Colors.white.withOpacity(0.1),
margin: EdgeInsets.symmetric(vertical: 4),
),
// Derrotas
Container(
margin: EdgeInsets.only(bottom: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
data.defeats.toString(),
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.bold,
color: Colors.red,
height: 0.8,
),
),
SizedBox(width: 6),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Container(
width: 8,
height: 8,
margin: EdgeInsets.only(right: 4),
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
),
Text(
'DER',
style: TextStyle(
fontSize: 10,
color: Colors.white.withOpacity(0.8),
fontWeight: FontWeight.w600,
),
),
],
),
SizedBox(height: 2),
Text(
'${(data.defeatPercentage * 100).toStringAsFixed(0)}%',
style: TextStyle(
fontSize: 12,
color: Colors.red,
fontWeight: FontWeight.bold,
),
),
],
),
),
],
),
),
// Divisor sutil
Container(
height: 0.5,
color: Colors.white.withOpacity(0.1),
margin: EdgeInsets.symmetric(vertical: 4),
),
// Total
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
data.total.toString(),
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.bold,
color: Colors.white,
height: 0.8,
),
),
SizedBox(width: 6),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Container(
width: 8,
height: 8,
margin: EdgeInsets.only(right: 4),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
),
Text(
'TOT',
style: TextStyle(
fontSize: 10,
color: Colors.white.withOpacity(0.8),
fontWeight: FontWeight.w600,
),
),
],
),
SizedBox(height: 2),
Text(
'100%',
style: TextStyle(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
],
),
),
],
),
], ],
), ),
), ),
@@ -359,37 +194,40 @@ class _PieChartCardState extends State<PieChartCard> with SingleTickerProviderSt
), ),
), ),
SizedBox(height: 10), // Espaço controlado SizedBox(height: 10 * sf),
// Win rate - Sempre visível e não sobreposto // Win rate - Com FittedBox para não estoirar
Container( Container(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), padding: EdgeInsets.symmetric(horizontal: 8 * sf, vertical: 6 * sf),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white.withOpacity(0.1), color: Colors.white.withOpacity(0.1),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12 * sf),
), ),
child: Row( child: FittedBox(
mainAxisAlignment: MainAxisAlignment.center, fit: BoxFit.scaleDown,
children: [ child: Row(
Icon( mainAxisAlignment: MainAxisAlignment.center,
data.victoryPercentage > 0.5 children: [
? Icons.trending_up Icon(
: Icons.trending_down, data.victoryPercentage > 0.5
color: data.victoryPercentage > 0.5 ? Icons.trending_up
? Colors.green : Icons.trending_down,
: Colors.red, color: data.victoryPercentage > 0.5
size: 18, // Pequeno ? Colors.green
), : Colors.red,
SizedBox(width: 8), size: 16 * sf,
Text(
'Win Rate: ${(data.victoryPercentage * 100).toStringAsFixed(1)}%',
style: TextStyle(
fontSize: 14, // Pequeno
fontWeight: FontWeight.bold,
color: Colors.white,
), ),
), SizedBox(width: 6 * sf),
], Text(
'Win Rate: ${(data.victoryPercentage * 100).toStringAsFixed(1)}%',
style: TextStyle(
fontSize: 12 * sf,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
), ),
), ),
], ],
@@ -401,4 +239,68 @@ class _PieChartCardState extends State<PieChartCard> with SingleTickerProviderSt
), ),
); );
} }
// Função auxiliar BLINDADA contra overflows
Widget _buildMiniStatRow(String label, String number, String percent, Color color, double sf) {
return Container(
margin: EdgeInsets.only(bottom: 4 * sf),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 28 * sf,
child: FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(
number,
style: TextStyle(fontSize: 22 * sf, fontWeight: FontWeight.bold, color: color, height: 1.0),
),
),
),
SizedBox(width: 4 * sf),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
FittedBox(
fit: BoxFit.scaleDown,
child: Row(
children: [
Container(
width: 6 * sf,
height: 6 * sf,
margin: EdgeInsets.only(right: 3 * sf),
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
),
Text(
label,
style: TextStyle(fontSize: 9 * sf, color: Colors.white.withOpacity(0.8), fontWeight: FontWeight.w600),
),
],
),
),
FittedBox(
fit: BoxFit.scaleDown,
child: Text(
'$percent%',
style: TextStyle(fontSize: 10 * sf, color: color, fontWeight: FontWeight.bold),
),
),
],
),
),
],
),
);
}
Widget _buildDivider(double sf) {
return Container(
height: 0.5,
color: Colors.white.withOpacity(0.1),
margin: EdgeInsets.symmetric(vertical: 3 * sf),
);
}
} }

View File

@@ -6,32 +6,38 @@ class PieChartWidget extends StatelessWidget {
final double defeatPercentage; final double defeatPercentage;
final double drawPercentage; final double drawPercentage;
final double size; final double size;
final double sf; // <-- Fator de Escala
const PieChartWidget({ const PieChartWidget({
super.key, super.key,
required this.victoryPercentage, required this.victoryPercentage,
required this.defeatPercentage, required this.defeatPercentage,
this.drawPercentage = 0, this.drawPercentage = 0,
this.size = 140, // Aumentado para 400x300 this.size = 140,
required this.sf, // <-- Obrigatório agora
}); });
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// Aplica a escala ao tamanho total do quadrado do gráfico
final double scaledSize = size * sf;
return SizedBox( return SizedBox(
width: size, width: scaledSize,
height: size, height: scaledSize,
child: CustomPaint( child: CustomPaint(
painter: _PieChartPainter( painter: _PieChartPainter(
victoryPercentage: victoryPercentage, victoryPercentage: victoryPercentage,
defeatPercentage: defeatPercentage, defeatPercentage: defeatPercentage,
drawPercentage: drawPercentage, drawPercentage: drawPercentage,
sf: sf, // <-- Passar para desenhar a borda
), ),
child: _buildCenterLabels(), child: _buildCenterLabels(scaledSize),
), ),
); );
} }
Widget _buildCenterLabels() { Widget _buildCenterLabels(double scaledSize) {
return Center( return Center(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@@ -39,16 +45,16 @@ class PieChartWidget extends StatelessWidget {
Text( Text(
'${(victoryPercentage * 100).toStringAsFixed(1)}%', '${(victoryPercentage * 100).toStringAsFixed(1)}%',
style: TextStyle( style: TextStyle(
fontSize: size * 0.2, // Tamanho responsivo (28px para 140px) fontSize: scaledSize * 0.144, // Mantém-se proporcional
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: Colors.white, color: Colors.white,
), ),
), ),
SizedBox(height: 4), SizedBox(height: 4 * sf),
Text( Text(
'Vitórias', 'Vitórias',
style: TextStyle( style: TextStyle(
fontSize: size * 0.1, // Tamanho responsivo (14px para 140px) fontSize: scaledSize * 0.1, // Mantém-se proporcional
color: Colors.white.withOpacity(0.8), color: Colors.white.withOpacity(0.8),
), ),
), ),
@@ -62,17 +68,20 @@ class _PieChartPainter extends CustomPainter {
final double victoryPercentage; final double victoryPercentage;
final double defeatPercentage; final double defeatPercentage;
final double drawPercentage; final double drawPercentage;
final double sf; // <-- Escala no pintor
_PieChartPainter({ _PieChartPainter({
required this.victoryPercentage, required this.victoryPercentage,
required this.defeatPercentage, required this.defeatPercentage,
required this.drawPercentage, required this.drawPercentage,
required this.sf,
}); });
@override @override
void paint(Canvas canvas, Size size) { void paint(Canvas canvas, Size size) {
final center = Offset(size.width / 2, size.height / 2); final center = Offset(size.width / 2, size.height / 2);
final radius = size.width / 2 - 5; // Aplica a escala à margem para não cortar a linha da borda num ecrã pequeno
final radius = size.width / 2 - (5 * sf);
// Cores // Cores
const victoryColor = Colors.green; const victoryColor = Colors.green;
@@ -106,7 +115,7 @@ class _PieChartPainter extends CustomPainter {
final borderPaint = Paint() final borderPaint = Paint()
..color = borderColor ..color = borderColor
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = 2; ..strokeWidth = 2 * sf; // <-- Escala na grossura da linha
canvas.drawCircle(center, radius, borderPaint); canvas.drawCircle(center, radius, borderPaint);
} }
@@ -130,7 +139,7 @@ class _PieChartPainter extends CustomPainter {
final linePaint = Paint() final linePaint = Paint()
..color = Colors.white.withOpacity(0.5) ..color = Colors.white.withOpacity(0.5)
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = 1.5; ..strokeWidth = 1.5 * sf; // <-- Escala na grossura da linha
final lineX = center.dx + radius * math.cos(startAngle); final lineX = center.dx + radius * math.cos(startAngle);
final lineY = center.dy + radius * math.sin(startAngle); final lineY = center.dy + radius * math.sin(startAngle);

View File

@@ -41,7 +41,7 @@ class _PlacarPageState extends State<PlacarPage> {
super.dispose(); super.dispose();
} }
// --- BOTÕES FLUTUANTES DE FALTA (MUITO MAIS PEQUENOS AQUI 👇) --- // --- BOTÕES FLUTUANTES DE FALTA ---
Widget _buildFloatingFoulBtn(String label, Color color, String action, IconData icon, double left, double right, double top, double sf) { Widget _buildFloatingFoulBtn(String label, Color color, String action, IconData icon, double left, double right, double top, double sf) {
return Positioned( return Positioned(
top: top, top: top,
@@ -52,20 +52,20 @@ class _PlacarPageState extends State<PlacarPage> {
feedback: Material( feedback: Material(
color: Colors.transparent, color: Colors.transparent,
child: CircleAvatar( child: CircleAvatar(
radius: 25 * sf, // Era 35 radius: 30 * sf,
backgroundColor: color.withOpacity(0.8), backgroundColor: color.withOpacity(0.8),
child: Icon(icon, color: Colors.white, size: 25 * sf) // Era 35 child: Icon(icon, color: Colors.white, size: 30 * sf)
), ),
), ),
child: Column( child: Column(
children: [ children: [
CircleAvatar( CircleAvatar(
radius: 22 * sf, // Era 30 radius: 27 * sf,
backgroundColor: color, backgroundColor: color,
child: Icon(icon, color: Colors.white, size: 26 * sf), // Era 35 child: Icon(icon, color: Colors.white, size: 28 * sf),
), ),
SizedBox(height: 4 * sf), SizedBox(height: 5 * sf),
Text(label, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 11 * sf)), // Era 14 Text(label, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12 * sf)),
], ],
), ),
), ),
@@ -80,12 +80,12 @@ class _PlacarPageState extends State<PlacarPage> {
child: FloatingActionButton( child: FloatingActionButton(
heroTag: heroTag, heroTag: heroTag,
backgroundColor: color, backgroundColor: color,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12 * (size / 50))), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14 * (size / 50))),
elevation: 4, elevation: 5,
onPressed: isLoading ? null : onTap, onPressed: isLoading ? null : onTap,
child: isLoading child: isLoading
? SizedBox(width: size*0.4, height: size*0.4, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2)) ? SizedBox(width: size*0.45, height: size*0.45, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2.5))
: Icon(icon, color: Colors.white, size: size * 0.5), : Icon(icon, color: Colors.white, size: size * 0.55),
), ),
); );
} }
@@ -94,9 +94,11 @@ class _PlacarPageState extends State<PlacarPage> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final double wScreen = MediaQuery.of(context).size.width; final double wScreen = MediaQuery.of(context).size.width;
final double hScreen = MediaQuery.of(context).size.height; final double hScreen = MediaQuery.of(context).size.height;
final double sf = math.min(wScreen / 1280, hScreen / 800);
// 👇 DIVISOR AUMENTADO PARA O 'sf' FICAR MAIS PEQUENO 👇
final double sf = math.min(wScreen / 1150, hScreen / 720);
final double cornerBtnSize = 50 * sf; final double cornerBtnSize = 48 * sf; // Tamanho ideal (Nem 38 nem 55)
if (_controller.isLoading) { if (_controller.isLoading) {
return Scaffold( return Scaffold(
@@ -105,8 +107,8 @@ class _PlacarPageState extends State<PlacarPage> {
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Text("PREPARANDO O PAVILHÃO", style: TextStyle(color: Colors.white24, fontSize: 40 * sf, fontWeight: FontWeight.bold, letterSpacing: 2)), Text("PREPARANDO O PAVILHÃO", style: TextStyle(color: Colors.white24, fontSize: 45 * sf, fontWeight: FontWeight.bold, letterSpacing: 2)),
SizedBox(height: 30 * sf), SizedBox(height: 35 * sf),
StreamBuilder( StreamBuilder(
stream: Stream.periodic(const Duration(seconds: 3)), stream: Stream.periodic(const Duration(seconds: 3)),
builder: (context, snapshot) { builder: (context, snapshot) {
@@ -118,7 +120,7 @@ class _PlacarPageState extends State<PlacarPage> {
"Os jogadores estão a terminar o aquecimento..." "Os jogadores estão a terminar o aquecimento..."
]; ];
String frase = frases[DateTime.now().second % frases.length]; String frase = frases[DateTime.now().second % frases.length];
return Text(frase, style: TextStyle(color: Colors.orange.withOpacity(0.7), fontSize: 24 * sf, fontStyle: FontStyle.italic)); return Text(frase, style: TextStyle(color: Colors.orange.withOpacity(0.7), fontSize: 26 * sf, fontStyle: FontStyle.italic));
}, },
), ),
], ],
@@ -130,12 +132,14 @@ class _PlacarPageState extends State<PlacarPage> {
return Scaffold( return Scaffold(
backgroundColor: const Color(0xFF266174), backgroundColor: const Color(0xFF266174),
body: SafeArea( body: SafeArea(
top: false,
bottom: false,
child: Stack( child: Stack(
children: [ children: [
// --- O CAMPO --- // --- O CAMPO ---
Container( Container(
margin: EdgeInsets.only(left: 60 * sf, right: 60 * sf, bottom: 50 * sf), margin: EdgeInsets.only(left: 65 * sf, right: 65 * sf, bottom: 55 * sf),
decoration: BoxDecoration(border: Border.all(color: Colors.white, width: 2.0)), decoration: BoxDecoration(border: Border.all(color: Colors.white, width: 2.5)),
child: LayoutBuilder( child: LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final w = constraints.maxWidth; final w = constraints.maxWidth;
@@ -151,12 +155,14 @@ class _PlacarPageState extends State<PlacarPage> {
}, },
child: Container( child: Container(
decoration: const BoxDecoration( decoration: const BoxDecoration(
image: DecorationImage(image: AssetImage('assets/campo.png'), fit: BoxFit.cover, alignment: Alignment(0.0, 0.2)), image: DecorationImage(
), image: AssetImage('assets/campo.png'),
fit: BoxFit.fill, // <-- A MÁGICA ESTÁ AQUI
), ),
child: Stack( child: Stack(
children: _controller.matchShots.map((shot) => Positioned( children: _controller.matchShots.map((shot) => Positioned(
left: shot.position.dx - (8 * sf), top: shot.position.dy - (8 * sf), left: shot.position.dx - (9 * sf), top: shot.position.dy - (9 * sf),
child: CircleAvatar(radius: 8 * sf, backgroundColor: shot.isMake ? Colors.green : Colors.red, child: Icon(shot.isMake ? Icons.check : Icons.close, size: 10 * sf, color: Colors.white)), child: CircleAvatar(radius: 9 * sf, backgroundColor: shot.isMake ? Colors.green : Colors.red, child: Icon(shot.isMake ? Icons.check : Icons.close, size: 11 * sf, color: Colors.white)),
)).toList(), )).toList(),
), ),
), ),
@@ -179,27 +185,32 @@ class _PlacarPageState extends State<PlacarPage> {
// --- BOTÕES DE FALTAS --- // --- BOTÕES DE FALTAS ---
if (!_controller.isSelectingShotLocation) ...[ if (!_controller.isSelectingShotLocation) ...[
_buildFloatingFoulBtn("FALTA +", Colors.orange, "add_foul", Icons.sports, w * 0.38, 0.0, h * 0.30, sf), _buildFloatingFoulBtn("FALTA +", Colors.orange, "add_foul", Icons.sports, w * 0.39, 0.0, h * 0.31, sf),
_buildFloatingFoulBtn("FALTA -", Colors.redAccent, "sub_foul", Icons.block, 0.0, w * 0.38, h * 0.30, sf), _buildFloatingFoulBtn("FALTA -", Colors.redAccent, "sub_foul", Icons.block, 0.0, w * 0.39, h * 0.31, sf),
], ],
// --- BOTÃO PLAY/PAUSE --- // --- BOTÃO PLAY/PAUSE ---
if (!_controller.isSelectingShotLocation) if (!_controller.isSelectingShotLocation)
Positioned( Positioned(
top: (h * 0.30) + (100 * sf), left: 0, right: 0,
child: Center(
child: GestureDetector(
onTap: () => _controller.toggleTimer(context),
child: CircleAvatar(radius: 60 * sf, backgroundColor: Colors.grey.withOpacity(0.5), child: Icon(_controller.isRunning ? Icons.pause : Icons.play_arrow, color: Colors.white, size: 50 * sf)),
),
),
),
top: (h * 0.32) + (40 * sf),
left: 0, right: 0,
child: Center(
child: GestureDetector(
onTap: () => _controller.toggleTimer(context),
child: CircleAvatar(
radius: 68 * sf,
backgroundColor: Colors.grey.withOpacity(0.5),
child: Icon(_controller.isRunning ? Icons.pause : Icons.play_arrow, color: Colors.white, size: 58 * sf)
),
),
),
),
// --- PLACAR NO TOPO --- // --- PLACAR NO TOPO ---
Positioned(top: 0, left: 0, right: 0, child: Center(child: TopScoreboard(controller: _controller, sf: sf))), Positioned(top: 0, left: 0, right: 0, child: Center(child: TopScoreboard(controller: _controller, sf: sf))),
// --- BOTÕES DE AÇÃO --- // --- BOTÕES DE AÇÃO ---
if (!_controller.isSelectingShotLocation) Positioned(bottom: 10 * sf, left: 0, right: 0, child: ActionButtonsPanel(controller: _controller, sf: sf)), if (!_controller.isSelectingShotLocation) Positioned(bottom: -10 * sf, left: 0, right: 0, child: ActionButtonsPanel(controller: _controller, sf: sf)),
// --- OVERLAY LANÇAMENTO --- // --- OVERLAY LANÇAMENTO ---
if (_controller.isSelectingShotLocation) if (_controller.isSelectingShotLocation)
@@ -207,9 +218,9 @@ class _PlacarPageState extends State<PlacarPage> {
top: h * 0.4, left: 0, right: 0, top: h * 0.4, left: 0, right: 0,
child: Center( child: Center(
child: Container( child: Container(
padding: EdgeInsets.symmetric(horizontal: 30 * sf, vertical: 15 * sf), padding: EdgeInsets.symmetric(horizontal: 35 * sf, vertical: 18 * sf),
decoration: BoxDecoration(color: Colors.black87, borderRadius: BorderRadius.circular(10 * sf), border: Border.all(color: Colors.white)), decoration: BoxDecoration(color: Colors.black87, borderRadius: BorderRadius.circular(11 * sf), border: Border.all(color: Colors.white, width: 1.5 * sf)),
child: Text("TOQUE NO CAMPO PARA MARCAR O LOCAL DO LANÇAMENTO", style: TextStyle(color: Colors.white, fontSize: 24 * sf, fontWeight: FontWeight.bold)), child: Text("TOQUE NO CAMPO PARA MARCAR O LOCAL DO LANÇAMENTO", style: TextStyle(color: Colors.white, fontSize: 27 * sf, fontWeight: FontWeight.bold)),
), ),
), ),
), ),
@@ -220,46 +231,73 @@ class _PlacarPageState extends State<PlacarPage> {
), ),
// --- BOTÕES LATERAIS --- // --- BOTÕES LATERAIS ---
if (!_controller.isSelectingShotLocation) ...[ // Topo Esquerdo: Guardar e Sair (Botão Único)
// Topo Esquerdo: Guardar e Sair Positioned(
Positioned( top: 50 * sf, left: 12 * sf,
top: 20 * sf, left: 10 * sf, child: _buildCornerBtn(
child: Column( heroTag: 'btn_save_exit',
children: [ icon: Icons.save_alt, // Mudei o ícone para dar a ideia de "Guardar e Sair"
_buildCornerBtn(heroTag: 'btn_save', icon: Icons.save, color: const Color(0xFF16202C), size: cornerBtnSize, isLoading: _controller.isSaving, onTap: () => _controller.saveGameStats(context)), color: const Color(0xFFD92C2C), // Mantive vermelho para saberes que é para fechar
SizedBox(height: 15 * sf), size: cornerBtnSize,
_buildCornerBtn(heroTag: 'btn_exit', icon: Icons.exit_to_app, color: const Color(0xFFD92C2C), size: cornerBtnSize, onTap: () => Navigator.pop(context)), isLoading: _controller.isSaving,
], onTap: () async {
) // 1. Primeiro obriga a guardar os dados na BD
), await _controller.saveGameStats(context);
// 2. Só depois de acabar de guardar é que volta para trás (sai da página)
if (context.mounted) {
Navigator.pop(context);
}
}
),
),
// Base Esquerda: Banco Casa // Base Esquerda: Banco Casa + TIMEOUT DA CASA
Positioned( Positioned(
bottom: 50 * sf, left: 10 * sf, bottom: 55 * sf, left: 12 * sf,
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
if (_controller.showMyBench) BenchPlayersList(controller: _controller, isOpponent: false, sf: sf), if (_controller.showMyBench) BenchPlayersList(controller: _controller, isOpponent: false, sf: sf),
SizedBox(height: 10 * sf), SizedBox(height: 12 * sf),
_buildCornerBtn(heroTag: 'btn_sub_home', icon: Icons.swap_horiz, color: const Color(0xFF1E5BB2), size: cornerBtnSize, onTap: () { _controller.showMyBench = !_controller.showMyBench; _controller.onUpdate(); }) _buildCornerBtn(heroTag: 'btn_sub_home', icon: Icons.swap_horiz, color: const Color(0xFF1E5BB2), size: cornerBtnSize, onTap: () { _controller.showMyBench = !_controller.showMyBench; _controller.onUpdate(); }),
SizedBox(height: 12 * sf),
_buildCornerBtn(
heroTag: 'btn_to_home',
icon: Icons.timer,
color: _controller.myTimeoutsUsed >= 3 ? Colors.grey : const Color(0xFF1E5BB2),
size: cornerBtnSize,
onTap: _controller.myTimeoutsUsed >= 3
? () => ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('🛑 A equipa da casa já usou os 3 Timeouts deste período!'), backgroundColor: Colors.red))
: () => _controller.useTimeout(false)
),
], ],
), ),
), ),
// Base Direita: Banco Visitante // Base Direita: Banco Visitante + TIMEOUT DO VISITANTE
Positioned( Positioned(
bottom: 50 * sf, right: 10 * sf, bottom: 55 * sf, right: 12 * sf,
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
if (_controller.showOppBench) BenchPlayersList(controller: _controller, isOpponent: true, sf: sf), if (_controller.showOppBench) BenchPlayersList(controller: _controller, isOpponent: true, sf: sf),
SizedBox(height: 10 * sf), SizedBox(height: 12 * sf),
_buildCornerBtn(heroTag: 'btn_sub_away', icon: Icons.swap_horiz, color: const Color(0xFFD92C2C), size: cornerBtnSize, onTap: () { _controller.showOppBench = !_controller.showOppBench; _controller.onUpdate(); }) _buildCornerBtn(heroTag: 'btn_sub_away', icon: Icons.swap_horiz, color: const Color(0xFFD92C2C), size: cornerBtnSize, onTap: () { _controller.showOppBench = !_controller.showOppBench; _controller.onUpdate(); }),
SizedBox(height: 12 * sf),
_buildCornerBtn(
heroTag: 'btn_to_away',
icon: Icons.timer,
color: _controller.opponentTimeoutsUsed >= 3 ? Colors.grey : const Color(0xFFD92C2C),
size: cornerBtnSize,
onTap: _controller.opponentTimeoutsUsed >= 3
? () => ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('🛑 A equipa visitante já usou os 3 Timeouts deste período!'), backgroundColor: Colors.red))
: () => _controller.useTimeout(true)
),
], ],
), ),
), ),
], ],
],
), ),
), ),
); );

View File

@@ -3,6 +3,7 @@ import '../controllers/game_controller.dart';
import '../controllers/team_controller.dart'; import '../controllers/team_controller.dart';
import '../models/game_model.dart'; import '../models/game_model.dart';
import '../widgets/game_widgets.dart'; import '../widgets/game_widgets.dart';
import 'dart:math' as math; // <-- IMPORTANTE: Para o cálculo da escala
class GamePage extends StatefulWidget { class GamePage extends StatefulWidget {
const GamePage({super.key}); const GamePage({super.key});
@@ -17,10 +18,15 @@ class _GamePageState extends State<GamePage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// 👇 CÁLCULO DA ESCALA (sf) PARA SE ADAPTAR A QUALQUER ECRÃ 👇
final double wScreen = MediaQuery.of(context).size.width;
final double hScreen = MediaQuery.of(context).size.height;
final double sf = math.min(wScreen, hScreen) / 400;
return Scaffold( return Scaffold(
backgroundColor: const Color(0xFFF5F7FA), backgroundColor: const Color(0xFFF5F7FA),
appBar: AppBar( appBar: AppBar(
title: const Text("Jogos", style: TextStyle(fontWeight: FontWeight.bold)), title: Text("Jogos", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20 * sf)),
backgroundColor: Colors.white, backgroundColor: Colors.white,
elevation: 0, elevation: 0,
), ),
@@ -39,15 +45,15 @@ class _GamePageState extends State<GamePage> {
} }
if (gameSnapshot.hasError) { if (gameSnapshot.hasError) {
return Center(child: Text("Erro: ${gameSnapshot.error}")); return Center(child: Text("Erro: ${gameSnapshot.error}", style: TextStyle(fontSize: 14 * sf)));
} }
if (!gameSnapshot.hasData || gameSnapshot.data!.isEmpty) { if (!gameSnapshot.hasData || gameSnapshot.data!.isEmpty) {
return const Center(child: Text("Nenhum jogo registado.")); return Center(child: Text("Nenhum jogo registado.", style: TextStyle(fontSize: 16 * sf)));
} }
return ListView.builder( return ListView.builder(
padding: const EdgeInsets.all(16), padding: EdgeInsets.all(16 * sf),
itemCount: gameSnapshot.data!.length, itemCount: gameSnapshot.data!.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final game = gameSnapshot.data![index]; final game = gameSnapshot.data![index];
@@ -65,7 +71,6 @@ class _GamePageState extends State<GamePage> {
} }
} }
// Agora já passamos as imagens para o cartão!
return GameResultCard( return GameResultCard(
gameId: game.id, gameId: game.id,
myTeam: game.myTeam, myTeam: game.myTeam,
@@ -74,8 +79,9 @@ class _GamePageState extends State<GamePage> {
opponentScore: game.opponentScore, opponentScore: game.opponentScore,
status: game.status, status: game.status,
season: game.season, season: game.season,
myTeamLogo: myLogo, // <-- IMAGEM DA TUA EQUIPA myTeamLogo: myLogo,
opponentTeamLogo: oppLogo, // <-- IMAGEM DA EQUIPA ADVERSÁRIA opponentTeamLogo: oppLogo,
sf: sf, // <-- Passamos a escala para o Cartão
); );
}, },
); );
@@ -85,18 +91,19 @@ class _GamePageState extends State<GamePage> {
), ),
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(
backgroundColor: const Color(0xFFE74C3C), backgroundColor: const Color(0xFFE74C3C),
child: const Icon(Icons.add, color: Colors.white), child: Icon(Icons.add, color: Colors.white, size: 24 * sf),
onPressed: () => _showCreateDialog(context), onPressed: () => _showCreateDialog(context, sf),
), ),
); );
} }
void _showCreateDialog(BuildContext context) { void _showCreateDialog(BuildContext context, double sf) {
showDialog( showDialog(
context: context, context: context,
builder: (context) => CreateGameDialogManual( builder: (context) => CreateGameDialogManual(
teamController: teamController, teamController: teamController,
gameController: gameController, gameController: gameController,
sf: sf, // <-- Passamos a escala para o Pop-up
), ),
); );
} }

View File

@@ -3,6 +3,9 @@ import 'package:playmaker/classe/home.config.dart';
import 'package:playmaker/grafico%20de%20pizza/grafico.dart'; import 'package:playmaker/grafico%20de%20pizza/grafico.dart';
import 'package:playmaker/pages/gamePage.dart'; import 'package:playmaker/pages/gamePage.dart';
import 'package:playmaker/pages/teamPage.dart'; import 'package:playmaker/pages/teamPage.dart';
import 'package:playmaker/controllers/team_controller.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'dart:math' as math;
class HomeScreen extends StatefulWidget { class HomeScreen extends StatefulWidget {
const HomeScreen({super.key}); const HomeScreen({super.key});
@@ -13,53 +16,50 @@ class HomeScreen extends StatefulWidget {
class _HomeScreenState extends State<HomeScreen> { class _HomeScreenState extends State<HomeScreen> {
int _selectedIndex = 0; int _selectedIndex = 0;
final TeamController _teamController = TeamController();
String? _selectedTeamId;
String _selectedTeamName = "Selecionar Equipa";
// Instância do Supabase para buscar as estatísticas
late final List<Widget> _pages; final _supabase = Supabase.instance.client;
@override @override
void initState() { Widget build(BuildContext context) {
super.initState(); final double wScreen = MediaQuery.of(context).size.width;
_pages = [ final double hScreen = MediaQuery.of(context).size.height;
_buildHomeContent(), final double sf = math.min(wScreen, hScreen) / 400;
final List<Widget> pages = [
_buildHomeContent(sf, wScreen),
const GamePage(), const GamePage(),
const TeamsPage(), const TeamsPage(),
const Center(child: Text('Tela de Status')), const Center(child: Text('Tela de Status')),
]; ];
}
void _onItemSelected(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold( return Scaffold(
backgroundColor: Colors.white, backgroundColor: Colors.white,
appBar: AppBar( appBar: AppBar(
title: const Text('PlayMaker'), title: Text('PlayMaker', style: TextStyle(fontSize: 20 * sf)),
backgroundColor: HomeConfig.primaryColor, backgroundColor: HomeConfig.primaryColor,
foregroundColor: Colors.white, foregroundColor: Colors.white,
leading: IconButton( leading: IconButton(
icon: const Icon(Icons.person), icon: Icon(Icons.person, size: 24 * sf),
onPressed: () {}, onPressed: () {},
), ),
), ),
body: IndexedStack( body: IndexedStack(
index: _selectedIndex, index: _selectedIndex,
children: _pages, children: pages,
), ),
bottomNavigationBar: NavigationBar( bottomNavigationBar: NavigationBar(
selectedIndex: _selectedIndex, selectedIndex: _selectedIndex,
onDestinationSelected: _onItemSelected, onDestinationSelected: (index) => setState(() => _selectedIndex = index),
backgroundColor: Theme.of(context).colorScheme.surface, backgroundColor: Theme.of(context).colorScheme.surface,
surfaceTintColor: Theme.of(context).colorScheme.surfaceTint, surfaceTintColor: Theme.of(context).colorScheme.surfaceTint,
elevation: 1, elevation: 1,
height: 70, height: 70 * math.min(sf, 1.2),
destinations: const [ destinations: const [
NavigationDestination( NavigationDestination(
icon: Icon(Icons.home_outlined), icon: Icon(Icons.home_outlined),
@@ -85,136 +85,230 @@ class _HomeScreenState extends State<HomeScreen> {
), ),
); );
} }
Widget _buildHomeContent() {
return SingleChildScrollView( // --- POPUP DE SELEÇÃO DE EQUIPA ---
child: Padding( void _showTeamSelector(BuildContext context, double sf) {
padding: const EdgeInsets.all(20.0), showModalBottomSheet(
child: Column( context: context,
crossAxisAlignment: CrossAxisAlignment.start, shape: RoundedRectangleBorder(
children: [ borderRadius: BorderRadius.vertical(top: Radius.circular(20 * sf)),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildStatCard(
title: 'Mais Pontos',
playerName: 'Michael Jordan',
statValue: '34.5',
statLabel: 'PPG',
color: Colors.blue[800]!,
icon: Icons.sports_basketball,
isHighlighted: true,
),
const SizedBox(width: 20),
_buildStatCard(
title: 'Mais Assistências',
playerName: 'Magic Johnson',
statValue: '12.8',
statLabel: 'APG',
color: Colors.green[800]!,
icon: Icons.sports_basketball,
isHighlighted: false,
),
],
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildStatCard(
title: 'Mais Rebotes',
playerName: 'Dennis Rodman',
statValue: '15.3',
statLabel: 'RPG',
color: Colors.purple[800]!,
icon: Icons.sports_basketball,
isHighlighted: false,
),
const SizedBox(width: 20),
PieChartCard(
title: 'DESEMPENHO',
subtitle: 'Vitórias vs Derrotas',
backgroundColor: Colors.red[800]!,
onTap: () {},
),
],
),
const SizedBox(height: 40),
Text(
'Histórico de Jogos',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.grey[800],
),
),
],
),
), ),
builder: (context) {
return StreamBuilder<List<Map<String, dynamic>>>(
stream: _teamController.teamsStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const SizedBox(height: 200, child: Center(child: CircularProgressIndicator()));
}
if (!snapshot.hasData || snapshot.data!.isEmpty) {
return SizedBox(height: 200 * sf, child: Center(child: Text("Nenhuma equipa criada.")));
}
final teams = snapshot.data!;
return ListView.builder(
shrinkWrap: true,
itemCount: teams.length,
itemBuilder: (context, index) {
final team = teams[index];
return ListTile(
title: Text(team['name']),
onTap: () {
setState(() {
_selectedTeamId = team['id'];
_selectedTeamName = team['name'];
});
Navigator.pop(context);
},
);
},
);
},
);
},
); );
} }
Widget _buildStatCard({ Widget _buildHomeContent(double sf, double wScreen) {
required String title, final double cardWidth = (wScreen - (40 * sf) - (20 * sf)) / 2;
required String playerName, final double cardHeight = cardWidth * 1.4; // Ajustado para não cortar conteúdo
required String statValue,
required String statLabel, return StreamBuilder<List<Map<String, dynamic>>>(
required Color color, // Buscar estatísticas de todos os jogadores da equipa selecionada
required IconData icon, stream: _selectedTeamId != null
bool isHighlighted = false, ? _supabase.from('player_stats_with_names').stream(primaryKey: ['id']).eq('team_id', _selectedTeamId!)
}) { : const Stream.empty(),
return SizedBox( builder: (context, snapshot) {
width: HomeConfig.cardwidthPadding, // Lógica de cálculo de líderes
height: HomeConfig.cardheightPadding, Map<String, dynamic> leaders = _calculateLeaders(snapshot.data ?? []);
child: Card(
elevation: 0, return SingleChildScrollView(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: isHighlighted
? const BorderSide(color: Colors.amber, width: 2)
: BorderSide.none,
),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [color.withOpacity(0.9), color.withOpacity(0.7)],
),
),
child: Padding( child: Padding(
padding: const EdgeInsets.all(20.0), padding: EdgeInsets.all(20.0 * sf),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Row( // Seletor de Equipa
mainAxisAlignment: MainAxisAlignment.spaceBetween, InkWell(
children: [ onTap: () => _showTeamSelector(context, sf),
Expanded( child: Container(
child: Column( padding: EdgeInsets.all(12 * sf),
crossAxisAlignment: CrossAxisAlignment.start, decoration: BoxDecoration(
children: [ color: Colors.grey.shade100,
Text(title.toUpperCase(), style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: Colors.white70)), borderRadius: BorderRadius.circular(15 * sf),
Text(playerName, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white)), border: Border.all(color: Colors.grey.shade300),
], ),
), child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(Icons.shield, color: HomeConfig.primaryColor, size: 24 * sf),
SizedBox(width: 10 * sf),
Text(_selectedTeamName, style: TextStyle(fontSize: 16 * sf, fontWeight: FontWeight.bold)),
],
),
const Icon(Icons.arrow_drop_down),
],
),
),
),
SizedBox(height: 25 * sf),
// Primeira Linha: Pontos e Assistências
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildStatCard(
title: 'Mais Pontos',
playerName: leaders['pts_name'],
statValue: leaders['pts_val'].toString(),
statLabel: 'TOTAL',
color: const Color(0xFF1565C0),
icon: Icons.bolt,
isHighlighted: true,
sf: sf, cardWidth: cardWidth, cardHeight: cardHeight,
),
SizedBox(width: 20 * sf),
_buildStatCard(
title: 'Assistências',
playerName: leaders['ast_name'],
statValue: leaders['ast_val'].toString(),
statLabel: 'TOTAL',
color: const Color(0xFF2E7D32),
icon: Icons.star,
sf: sf, cardWidth: cardWidth, cardHeight: cardHeight,
), ),
if (isHighlighted) const Icon(Icons.star, color: Colors.amber, size: 20),
], ],
), ),
SizedBox(height: 20 * sf),
// Segunda Linha: Rebotes e Gráfico
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildStatCard(
title: 'Rebotes',
playerName: leaders['rbs_name'],
statValue: leaders['rbs_val'].toString(),
statLabel: 'TOTAL',
color: const Color(0xFF6A1B9A),
icon: Icons.trending_up,
sf: sf, cardWidth: cardWidth, cardHeight: cardHeight,
),
SizedBox(width: 20 * sf),
PieChartCard(
title: 'DESEMPENHO',
subtitle: 'Temporada',
backgroundColor: const Color(0xFFC62828),
onTap: () {},
sf: sf, cardWidth: cardWidth, cardHeight: cardHeight,
),
],
),
SizedBox(height: 40 * sf),
Text('Histórico de Jogos', style: TextStyle(fontSize: 24 * sf, fontWeight: FontWeight.bold, color: Colors.grey[800])),
],
),
),
);
},
);
}
Map<String, dynamic> _calculateLeaders(List<Map<String, dynamic>> data) {
Map<String, int> ptsMap = {};
Map<String, int> astMap = {};
Map<String, int> rbsMap = {};
Map<String, String> namesMap = {}; // Aqui vamos guardar o nome real
for (var row in data) {
String pid = row['member_id'].toString();
// 👇 BUSCA O NOME QUE VEM DA VIEW 👇
namesMap[pid] = row['player_name']?.toString() ?? "Desconhecido";
ptsMap[pid] = (ptsMap[pid] ?? 0) + (row['pts'] as int? ?? 0);
astMap[pid] = (astMap[pid] ?? 0) + (row['ast'] as int? ?? 0);
rbsMap[pid] = (rbsMap[pid] ?? 0) + (row['rbs'] as int? ?? 0);
}
// Se não houver dados, namesMap estará vazio e o reduce daria erro.
// Por isso, se estiver vazio, retornamos logo "---".
if (ptsMap.isEmpty) {
return {
'pts_name': '---', 'pts_val': 0,
'ast_name': '---', 'ast_val': 0,
'rbs_name': '---', 'rbs_val': 0,
};
}
String getBest(Map<String, int> map) {
var bestId = map.entries.reduce((a, b) => a.value > b.value ? a : b).key;
return namesMap[bestId]!;
}
int getBestVal(Map<String, int> map) => map.values.reduce((a, b) => a > b ? a : b);
return {
'pts_name': getBest(ptsMap), 'pts_val': getBestVal(ptsMap),
'ast_name': getBest(astMap), 'ast_val': getBestVal(astMap),
'rbs_name': getBest(rbsMap), 'rbs_val': getBestVal(rbsMap),
};
}
Widget _buildStatCard({
required String title, required String playerName, required String statValue,
required String statLabel, required Color color, required IconData icon,
bool isHighlighted = false, required double sf, required double cardWidth, required double cardHeight,
}) {
return SizedBox(
width: cardWidth, height: cardHeight,
child: Card(
elevation: 4,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20 * sf),
side: isHighlighted ? const BorderSide(color: Colors.amber, width: 2) : BorderSide.none,
),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20 * sf),
gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [color.withOpacity(0.9), color]),
),
child: Padding(
padding: EdgeInsets.all(16.0 * sf),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title.toUpperCase(), style: TextStyle(fontSize: 10 * sf, fontWeight: FontWeight.bold, color: Colors.white70)),
Text(playerName, style: TextStyle(fontSize: 14 * sf, fontWeight: FontWeight.bold, color: Colors.white), maxLines: 1, overflow: TextOverflow.ellipsis),
const Spacer(), const Spacer(),
Center( Center(child: Text(statValue, style: TextStyle(fontSize: 32 * sf, fontWeight: FontWeight.bold, color: Colors.white))),
child: Text(statValue, style: const TextStyle(fontSize: 38, fontWeight: FontWeight.bold, color: Colors.white)), Center(child: Text(statLabel, style: TextStyle(fontSize: 10 * sf, color: Colors.white70))),
),
Center(
child: Text(statLabel, style: const TextStyle(fontSize: 12, color: Colors.white70)),
),
const Spacer(), const Spacer(),
Container( Container(
width: double.infinity, width: double.infinity, padding: const EdgeInsets.symmetric(vertical: 6),
padding: const EdgeInsets.symmetric(vertical: 8),
decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(10)), decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(10)),
child: const Center(child: Text('VER DETALHES', style: TextStyle(color: Colors.white, fontSize: 12))), child: Center(child: Text('DETALHES', style: TextStyle(color: Colors.white, fontSize: 10 * sf))),
), ),
], ],
), ),

View File

@@ -3,6 +3,7 @@ import 'package:playmaker/screens/team_stats_page.dart';
import '../controllers/team_controller.dart'; import '../controllers/team_controller.dart';
import '../models/team_model.dart'; import '../models/team_model.dart';
import '../widgets/team_widgets.dart'; import '../widgets/team_widgets.dart';
import 'dart:math' as math; // <-- IMPORTANTE: Adicionar para o cálculo
class TeamsPage extends StatefulWidget { class TeamsPage extends StatefulWidget {
const TeamsPage({super.key}); const TeamsPage({super.key});
@@ -26,24 +27,24 @@ class _TeamsPageState extends State<TeamsPage> {
} }
// --- POPUP DE FILTROS --- // --- POPUP DE FILTROS ---
void _showFilterDialog(BuildContext context) { void _showFilterDialog(BuildContext context, double sf) {
showDialog( showDialog(
context: context, context: context,
builder: (context) { builder: (context) {
return StatefulBuilder( return StatefulBuilder(
builder: (context, setModalState) { builder: (context, setModalState) {
return AlertDialog( return AlertDialog(
backgroundColor: const Color(0xFF2C3E50), // 2. CORRIGIDO: Fundo escuro backgroundColor: const Color(0xFF2C3E50),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20 * sf)),
title: Row( title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
const Text( Text(
"Filtros de pesquisa", "Filtros de pesquisa",
style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold), style: TextStyle(color: Colors.white, fontSize: 18 * sf, fontWeight: FontWeight.bold),
), ),
IconButton( IconButton(
icon: const Icon(Icons.close, color: Colors.white, size: 20), icon: Icon(Icons.close, color: Colors.white, size: 20 * sf),
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
) )
], ],
@@ -52,7 +53,7 @@ class _TeamsPageState extends State<TeamsPage> {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
const Divider(color: Colors.white24), const Divider(color: Colors.white24),
const SizedBox(height: 16), SizedBox(height: 16 * sf),
Row( Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
@@ -62,19 +63,21 @@ class _TeamsPageState extends State<TeamsPage> {
title: "TEMPORADA", title: "TEMPORADA",
options: ['Todas', '2023/24', '2024/25', '2025/26'], options: ['Todas', '2023/24', '2024/25', '2025/26'],
currentValue: _selectedSeason, currentValue: _selectedSeason,
sf: sf,
onSelect: (val) { onSelect: (val) {
setState(() => _selectedSeason = val); setState(() => _selectedSeason = val);
setModalState(() {}); setModalState(() {});
}, },
), ),
), ),
const SizedBox(width: 20), SizedBox(width: 20 * sf),
// Coluna Ordenar // Coluna Ordenar
Expanded( Expanded(
child: _buildPopupColumn( child: _buildPopupColumn(
title: "ORDENAR POR", title: "ORDENAR POR",
options: ['Recentes', 'Nome', 'Tamanho'], options: ['Recentes', 'Nome', 'Tamanho'],
currentValue: _currentSort, currentValue: _currentSort,
sf: sf,
onSelect: (val) { onSelect: (val) {
setState(() => _currentSort = val); setState(() => _currentSort = val);
setModalState(() {}); setModalState(() {});
@@ -88,7 +91,7 @@ class _TeamsPageState extends State<TeamsPage> {
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
child: const Text("CONCLUÍDO", style: TextStyle(color: Color(0xFFE74C3C), fontWeight: FontWeight.bold)), child: Text("CONCLUÍDO", style: TextStyle(color: const Color(0xFFE74C3C), fontWeight: FontWeight.bold, fontSize: 14 * sf)),
), ),
], ],
); );
@@ -102,25 +105,26 @@ class _TeamsPageState extends State<TeamsPage> {
required String title, required String title,
required List<String> options, required List<String> options,
required String currentValue, required String currentValue,
required double sf,
required Function(String) onSelect, required Function(String) onSelect,
}) { }) {
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text(title, style: const TextStyle(color: Colors.grey, fontSize: 11, fontWeight: FontWeight.bold)), Text(title, style: TextStyle(color: Colors.grey, fontSize: 11 * sf, fontWeight: FontWeight.bold)),
const SizedBox(height: 12), SizedBox(height: 12 * sf),
...options.map((opt) { ...options.map((opt) {
final isSelected = currentValue == opt; final isSelected = currentValue == opt;
return InkWell( return InkWell(
onTap: () => onSelect(opt), onTap: () => onSelect(opt),
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0), padding: EdgeInsets.symmetric(vertical: 8.0 * sf),
child: Text( child: Text(
opt, opt,
style: TextStyle( style: TextStyle(
// 3. CORRIGIDO: Cor do texto (Branco se não selecionado, Vermelho se selecionado)
color: isSelected ? const Color(0xFFE74C3C) : Colors.white70, color: isSelected ? const Color(0xFFE74C3C) : Colors.white70,
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
fontSize: 14 * sf,
), ),
), ),
), ),
@@ -132,51 +136,57 @@ class _TeamsPageState extends State<TeamsPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// 👇 CÁLCULO DA ESCALA (sf) PARA SE ADAPTAR A QUALQUER ECRÃ 👇
final double wScreen = MediaQuery.of(context).size.width;
final double hScreen = MediaQuery.of(context).size.height;
final double sf = math.min(wScreen, hScreen) / 400;
return Scaffold( return Scaffold(
backgroundColor: const Color(0xFFF5F7FA), backgroundColor: const Color(0xFFF5F7FA),
appBar: AppBar( appBar: AppBar(
title: const Text("Minhas Equipas", style: TextStyle(fontWeight: FontWeight.bold)), title: Text("Minhas Equipas", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20 * sf)),
backgroundColor: const Color(0xFFF5F7FA), backgroundColor: const Color(0xFFF5F7FA),
elevation: 0, elevation: 0,
actions: [ actions: [
IconButton( IconButton(
icon: const Icon(Icons.filter_list, color: Color(0xFFE74C3C)), icon: Icon(Icons.filter_list, color: const Color(0xFFE74C3C), size: 24 * sf),
onPressed: () => _showFilterDialog(context), onPressed: () => _showFilterDialog(context, sf),
), ),
], ],
), ),
body: Column( body: Column(
children: [ children: [
_buildSearchBar(), _buildSearchBar(sf),
Expanded(child: _buildTeamsList()), Expanded(child: _buildTeamsList(sf)),
], ],
), ),
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(
backgroundColor: const Color(0xFFE74C3C), backgroundColor: const Color(0xFFE74C3C),
child: const Icon(Icons.add, color: Colors.white), child: Icon(Icons.add, color: Colors.white, size: 24 * sf),
onPressed: () => _showCreateDialog(context), onPressed: () => _showCreateDialog(context, sf),
), ),
); );
} }
Widget _buildSearchBar() { Widget _buildSearchBar(double sf) {
return Padding( return Padding(
padding: const EdgeInsets.all(16.0), padding: EdgeInsets.all(16.0 * sf),
child: TextField( child: TextField(
controller: _searchController, controller: _searchController,
onChanged: (v) => setState(() => _searchQuery = v.toLowerCase()), onChanged: (v) => setState(() => _searchQuery = v.toLowerCase()),
style: TextStyle(fontSize: 16 * sf),
decoration: InputDecoration( decoration: InputDecoration(
hintText: 'Pesquisar equipa...', hintText: 'Pesquisar equipa...',
prefixIcon: const Icon(Icons.search, color: Color(0xFFE74C3C)), hintStyle: TextStyle(fontSize: 16 * sf),
prefixIcon: Icon(Icons.search, color: const Color(0xFFE74C3C), size: 22 * sf),
filled: true, filled: true,
fillColor: Colors.white, fillColor: Colors.white,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: BorderSide.none), border: OutlineInputBorder(borderRadius: BorderRadius.circular(15 * sf), borderSide: BorderSide.none),
), ),
), ),
); );
} }
Widget _buildTeamsList() { Widget _buildTeamsList(double sf) {
return StreamBuilder<List<Map<String, dynamic>>>( return StreamBuilder<List<Map<String, dynamic>>>(
stream: controller.teamsStream, stream: controller.teamsStream,
builder: (context, snapshot) { builder: (context, snapshot) {
@@ -185,7 +195,7 @@ class _TeamsPageState extends State<TeamsPage> {
} }
if (!snapshot.hasData || snapshot.data!.isEmpty) { if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text("Nenhuma equipa encontrada.")); return Center(child: Text("Nenhuma equipa encontrada.", style: TextStyle(fontSize: 16 * sf)));
} }
var data = List<Map<String, dynamic>>.from(snapshot.data!); var data = List<Map<String, dynamic>>.from(snapshot.data!);
@@ -198,31 +208,25 @@ class _TeamsPageState extends State<TeamsPage> {
data = data.where((t) => t['name'].toString().toLowerCase().contains(_searchQuery)).toList(); data = data.where((t) => t['name'].toString().toLowerCase().contains(_searchQuery)).toList();
} }
// --- 2. ORDENAÇÃO (FAVORITOS PRIMEIRO) --- // --- 2. ORDENAÇÃO ---
data.sort((a, b) { data.sort((a, b) {
// Apanhar o estado de favorito (tratando null como false)
bool favA = a['is_favorite'] ?? false; bool favA = a['is_favorite'] ?? false;
bool favB = b['is_favorite'] ?? false; bool favB = b['is_favorite'] ?? false;
if (favA && !favB) return -1;
// REGRA 1: Favoritos aparecem sempre primeiro if (!favA && favB) return 1;
if (favA && !favB) return -1; // A sobe
if (!favA && favB) return 1; // B sobe
// REGRA 2: Se o estado de favorito for igual, aplica o filtro do utilizador
if (_currentSort == 'Nome') { if (_currentSort == 'Nome') {
return a['name'].toString().compareTo(b['name'].toString()); return a['name'].toString().compareTo(b['name'].toString());
} else { // Recentes } else {
return (b['created_at'] ?? '').toString().compareTo((a['created_at'] ?? '').toString()); return (b['created_at'] ?? '').toString().compareTo((a['created_at'] ?? '').toString());
} }
}); });
return ListView.builder( return ListView.builder(
padding: const EdgeInsets.symmetric(horizontal: 16), padding: EdgeInsets.symmetric(horizontal: 16 * sf),
itemCount: data.length, itemCount: data.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final team = Team.fromMap(data[index]); final team = Team.fromMap(data[index]);
// Navegação para estatísticas
return GestureDetector( return GestureDetector(
onTap: () { onTap: () {
Navigator.push( Navigator.push(
@@ -233,6 +237,7 @@ class _TeamsPageState extends State<TeamsPage> {
child: TeamCard( child: TeamCard(
team: team, team: team,
controller: controller, controller: controller,
sf: sf, // Passar a escala para o Card
onFavoriteTap: () => controller.toggleFavorite(team.id, team.isFavorite), onFavoriteTap: () => controller.toggleFavorite(team.id, team.isFavorite),
), ),
); );
@@ -242,14 +247,13 @@ class _TeamsPageState extends State<TeamsPage> {
); );
} }
void _showCreateDialog(BuildContext context) { void _showCreateDialog(BuildContext context, double sf) {
showDialog( showDialog(
context: context, context: context,
builder: (context) => CreateTeamDialog( builder: (context) => CreateTeamDialog(
sf: sf,
onConfirm: (name, season, imageUrl) => controller.createTeam(name, season, imageUrl), onConfirm: (name, season, imageUrl) => controller.createTeam(name, season, imageUrl),
), ),
); );
} }
} }

View File

@@ -1,5 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:playmaker/pages/PlacarPage.dart'; // Garante que o import está correto import 'package:playmaker/pages/PlacarPage.dart';
import '../controllers/team_controller.dart'; import '../controllers/team_controller.dart';
import '../controllers/game_controller.dart'; import '../controllers/game_controller.dart';
@@ -7,8 +7,9 @@ import '../controllers/game_controller.dart';
class GameResultCard extends StatelessWidget { class GameResultCard extends StatelessWidget {
final String gameId; final String gameId;
final String myTeam, opponentTeam, myScore, opponentScore, status, season; final String myTeam, opponentTeam, myScore, opponentScore, status, season;
final String? myTeamLogo; // NOVA VARIÁVEL final String? myTeamLogo;
final String? opponentTeamLogo; // NOVA VARIÁVEL final String? opponentTeamLogo;
final double sf; // NOVA VARIÁVEL DE ESCALA
const GameResultCard({ const GameResultCard({
super.key, super.key,
@@ -19,71 +20,70 @@ class GameResultCard extends StatelessWidget {
required this.opponentScore, required this.opponentScore,
required this.status, required this.status,
required this.season, required this.season,
this.myTeamLogo, // ADICIONADO AO CONSTRUTOR this.myTeamLogo,
this.opponentTeamLogo, // ADICIONADO AO CONSTRUTOR this.opponentTeamLogo,
required this.sf, // OBRIGATÓRIO RECEBER A ESCALA
}); });
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return Container(
margin: const EdgeInsets.only(bottom: 16), margin: EdgeInsets.only(bottom: 16 * sf),
padding: const EdgeInsets.all(16), padding: EdgeInsets.all(16 * sf),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white, color: Colors.white,
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20 * sf),
boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 10)], boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 10 * sf)],
), ),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
// Passamos a imagem para a função Expanded(child: _buildTeamInfo(myTeam, const Color(0xFFE74C3C), myTeamLogo, sf)),
Expanded(child: _buildTeamInfo(myTeam, const Color(0xFFE74C3C), myTeamLogo)), _buildScoreCenter(context, gameId, sf),
_buildScoreCenter(context, gameId), Expanded(child: _buildTeamInfo(opponentTeam, Colors.black87, opponentTeamLogo, sf)),
// Passamos a imagem para a função
Expanded(child: _buildTeamInfo(opponentTeam, Colors.black87, opponentTeamLogo)),
], ],
), ),
); );
} }
// ATUALIZADO para desenhar a imagem Widget _buildTeamInfo(String name, Color color, String? logoUrl, double sf) {
Widget _buildTeamInfo(String name, Color color, String? logoUrl) {
return Column( return Column(
children: [ children: [
CircleAvatar( CircleAvatar(
radius: 24 * sf, // Ajuste do tamanho do logo
backgroundColor: color, backgroundColor: color,
backgroundImage: (logoUrl != null && logoUrl.isNotEmpty) backgroundImage: (logoUrl != null && logoUrl.isNotEmpty)
? NetworkImage(logoUrl) ? NetworkImage(logoUrl)
: null, : null,
child: (logoUrl == null || logoUrl.isEmpty) child: (logoUrl == null || logoUrl.isEmpty)
? const Icon(Icons.shield, color: Colors.white) ? Icon(Icons.shield, color: Colors.white, size: 24 * sf)
: null, : null,
), ),
const SizedBox(height: 4), SizedBox(height: 6 * sf),
Text(name, Text(name,
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 12), style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13 * sf),
textAlign: TextAlign.center, textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
maxLines: 2, // Permite 2 linhas para nomes compridos não cortarem
), ),
], ],
); );
} }
Widget _buildScoreCenter(BuildContext context, String id) { Widget _buildScoreCenter(BuildContext context, String id, double sf) {
return Column( return Column(
children: [ children: [
Row( Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
_scoreBox(myScore, Colors.green), _scoreBox(myScore, Colors.green, sf),
const Text(" : ", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20)), Text(" : ", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 22 * sf)),
_scoreBox(opponentScore, Colors.grey), _scoreBox(opponentScore, Colors.grey, sf),
], ],
), ),
const SizedBox(height: 8), SizedBox(height: 10 * sf),
TextButton.icon( TextButton.icon(
onPressed: () { onPressed: () {
// NAVEGAÇÃO PARA O PLACAR (Usando o ID real)
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
@@ -95,25 +95,25 @@ class GameResultCard extends StatelessWidget {
), ),
); );
}, },
icon: const Icon(Icons.play_circle_fill, size: 16, color: Color(0xFFE74C3C)), icon: Icon(Icons.play_circle_fill, size: 18 * sf, color: const Color(0xFFE74C3C)),
label: const Text("RETORNAR", style: TextStyle(fontSize: 10, color: Color(0xFFE74C3C), fontWeight: FontWeight.bold)), label: Text("RETORNAR", style: TextStyle(fontSize: 11 * sf, color: const Color(0xFFE74C3C), fontWeight: FontWeight.bold)),
style: TextButton.styleFrom( style: TextButton.styleFrom(
backgroundColor: const Color(0xFFE74C3C).withOpacity(0.1), backgroundColor: const Color(0xFFE74C3C).withOpacity(0.1),
padding: const EdgeInsets.symmetric(horizontal: 12), padding: EdgeInsets.symmetric(horizontal: 14 * sf, vertical: 8 * sf),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20 * sf)),
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
), ),
), ),
const SizedBox(height: 4), SizedBox(height: 6 * sf),
Text(status, style: const TextStyle(fontSize: 10, color: Colors.blue, fontWeight: FontWeight.bold)), Text(status, style: TextStyle(fontSize: 12 * sf, color: Colors.blue, fontWeight: FontWeight.bold)),
], ],
); );
} }
Widget _scoreBox(String pts, Color c) => Container( Widget _scoreBox(String pts, Color c, double sf) => Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), padding: EdgeInsets.symmetric(horizontal: 12 * sf, vertical: 6 * sf),
decoration: BoxDecoration(color: c, borderRadius: BorderRadius.circular(8)), decoration: BoxDecoration(color: c, borderRadius: BorderRadius.circular(8 * sf)),
child: Text(pts, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), child: Text(pts, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16 * sf)),
); );
} }
@@ -121,11 +121,13 @@ class GameResultCard extends StatelessWidget {
class CreateGameDialogManual extends StatefulWidget { class CreateGameDialogManual extends StatefulWidget {
final TeamController teamController; final TeamController teamController;
final GameController gameController; final GameController gameController;
final double sf; // NOVA VARIÁVEL DE ESCALA
const CreateGameDialogManual({ const CreateGameDialogManual({
super.key, super.key,
required this.teamController, required this.teamController,
required this.gameController required this.gameController,
required this.sf,
}); });
@override @override
@@ -153,33 +155,46 @@ class _CreateGameDialogManualState extends State<CreateGameDialogManual> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return AlertDialog( return AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20 * widget.sf)),
title: const Text('Configurar Partida', style: TextStyle(fontWeight: FontWeight.bold)), title: Text('Configurar Partida', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18 * widget.sf)),
content: SingleChildScrollView( content: SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
TextField( TextField(
controller: _seasonController, controller: _seasonController,
decoration: const InputDecoration(labelText: 'Temporada', border: OutlineInputBorder(), prefixIcon: Icon(Icons.calendar_today)), style: TextStyle(fontSize: 14 * widget.sf),
decoration: InputDecoration(
labelText: 'Temporada',
labelStyle: TextStyle(fontSize: 14 * widget.sf),
border: const OutlineInputBorder(),
prefixIcon: Icon(Icons.calendar_today, size: 20 * widget.sf)
),
), ),
const SizedBox(height: 15), SizedBox(height: 15 * widget.sf),
_buildSearch(label: "Minha Equipa", controller: _myTeamController), _buildSearch(label: "Minha Equipa", controller: _myTeamController, sf: widget.sf),
const Padding(padding: EdgeInsets.symmetric(vertical: 8), child: Text("VS", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.grey))), Padding(
padding: EdgeInsets.symmetric(vertical: 10 * widget.sf),
child: Text("VS", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.grey, fontSize: 16 * widget.sf))
),
_buildSearch(label: "Adversário", controller: _opponentController), _buildSearch(label: "Adversário", controller: _opponentController, sf: widget.sf),
], ],
), ),
), ),
actions: [ actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('CANCELAR')), TextButton(
onPressed: () => Navigator.pop(context),
child: Text('CANCELAR', style: TextStyle(fontSize: 14 * widget.sf))
),
ElevatedButton( ElevatedButton(
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFFE74C3C), backgroundColor: const Color(0xFFE74C3C),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10 * widget.sf)),
padding: EdgeInsets.symmetric(horizontal: 16 * widget.sf, vertical: 10 * widget.sf)
), ),
onPressed: _isLoading ? null : () async { onPressed: _isLoading ? null : () async {
if (_myTeamController.text.isNotEmpty && _opponentController.text.isNotEmpty) { if (_myTeamController.text.isNotEmpty && _opponentController.text.isNotEmpty) {
@@ -210,15 +225,14 @@ class _CreateGameDialogManualState extends State<CreateGameDialogManual> {
} }
}, },
child: _isLoading child: _isLoading
? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2)) ? SizedBox(width: 20 * widget.sf, height: 20 * widget.sf, child: const CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
: const Text('CRIAR', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), : Text('CRIAR', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 14 * widget.sf)),
), ),
], ],
); );
} }
// ATUALIZADO para usar Map e mostrar a imagem na lista de pesquisa Widget _buildSearch({required String label, required TextEditingController controller, required double sf}) {
Widget _buildSearch({required String label, required TextEditingController controller}) {
return StreamBuilder<List<Map<String, dynamic>>>( return StreamBuilder<List<Map<String, dynamic>>>(
stream: widget.teamController.teamsStream, stream: widget.teamController.teamsStream,
builder: (context, snapshot) { builder: (context, snapshot) {
@@ -242,10 +256,9 @@ class _CreateGameDialogManualState extends State<CreateGameDialogManual> {
alignment: Alignment.topLeft, alignment: Alignment.topLeft,
child: Material( child: Material(
elevation: 4.0, elevation: 4.0,
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8 * sf),
child: ConstrainedBox( child: ConstrainedBox(
// Ajuste do tamanho máximo do pop-up de sugestões constraints: BoxConstraints(maxHeight: 250 * sf, maxWidth: MediaQuery.of(context).size.width * 0.7),
constraints: BoxConstraints(maxHeight: 250, maxWidth: MediaQuery.of(context).size.width * 0.7),
child: ListView.builder( child: ListView.builder(
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
shrinkWrap: true, shrinkWrap: true,
@@ -257,15 +270,16 @@ class _CreateGameDialogManualState extends State<CreateGameDialogManual> {
return ListTile( return ListTile(
leading: CircleAvatar( leading: CircleAvatar(
radius: 20 * sf,
backgroundColor: Colors.grey.shade200, backgroundColor: Colors.grey.shade200,
backgroundImage: (imageUrl != null && imageUrl.isNotEmpty) backgroundImage: (imageUrl != null && imageUrl.isNotEmpty)
? NetworkImage(imageUrl) ? NetworkImage(imageUrl)
: null, : null,
child: (imageUrl == null || imageUrl.isEmpty) child: (imageUrl == null || imageUrl.isEmpty)
? const Icon(Icons.shield, color: Colors.grey) ? Icon(Icons.shield, color: Colors.grey, size: 20 * sf)
: null, : null,
), ),
title: Text(name, style: const TextStyle(fontWeight: FontWeight.bold)), title: Text(name, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14 * sf)),
onTap: () { onTap: () {
onSelected(option); onSelected(option);
}, },
@@ -288,9 +302,11 @@ class _CreateGameDialogManualState extends State<CreateGameDialogManual> {
return TextField( return TextField(
controller: txtCtrl, controller: txtCtrl,
focusNode: node, focusNode: node,
style: TextStyle(fontSize: 14 * sf),
decoration: InputDecoration( decoration: InputDecoration(
labelText: label, labelText: label,
prefixIcon: const Icon(Icons.search), labelStyle: TextStyle(fontSize: 14 * sf),
prefixIcon: Icon(Icons.search, size: 20 * sf),
border: const OutlineInputBorder() border: const OutlineInputBorder()
), ),
); );

View File

@@ -1,5 +1,4 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:playmaker/classe/home.config.dart';
class StatCard extends StatelessWidget { class StatCard extends StatelessWidget {
final String title; final String title;
@@ -10,6 +9,11 @@ class StatCard extends StatelessWidget {
final IconData icon; final IconData icon;
final bool isHighlighted; final bool isHighlighted;
final VoidCallback? onTap; final VoidCallback? onTap;
// Variáveis novas para que o tamanho não fique preso à HomeConfig
final double sf;
final double cardWidth;
final double cardHeight;
const StatCard({ const StatCard({
super.key, super.key,
@@ -21,27 +25,30 @@ class StatCard extends StatelessWidget {
required this.icon, required this.icon,
this.isHighlighted = false, this.isHighlighted = false,
this.onTap, this.onTap,
this.sf = 1.0, // Default 1.0 para não dar erro se não passares o valor
required this.cardWidth,
required this.cardHeight,
}); });
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return SizedBox(
width: HomeConfig.cardwidthPadding, width: cardWidth,
height: HomeConfig.cardheightPadding, height: cardHeight,
child: Card( child: Card(
elevation: 0, elevation: 0,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20 * sf),
side: isHighlighted side: isHighlighted
? BorderSide(color: Colors.amber, width: 2) ? BorderSide(color: Colors.amber, width: 2 * sf)
: BorderSide.none, : BorderSide.none,
), ),
child: InkWell( child: InkWell(
onTap: onTap, onTap: onTap,
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20 * sf),
child: Container( child: Container(
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20 * sf),
gradient: LinearGradient( gradient: LinearGradient(
begin: Alignment.topCenter, begin: Alignment.topCenter,
end: Alignment.bottomCenter, end: Alignment.bottomCenter,
@@ -52,13 +59,14 @@ class StatCard extends StatelessWidget {
), ),
), ),
child: Padding( child: Padding(
padding: const EdgeInsets.all(20.0), padding: EdgeInsets.all(16.0 * sf),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// Cabeçalho // Cabeçalho
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Expanded( Expanded(
child: Column( child: Column(
@@ -66,12 +74,12 @@ class StatCard extends StatelessWidget {
children: [ children: [
Text( Text(
title.toUpperCase(), title.toUpperCase(),
style: HomeConfig.titleStyle, style: TextStyle(fontSize: 11 * sf, fontWeight: FontWeight.bold, color: Colors.white70),
), ),
SizedBox(height: 5), SizedBox(height: 2 * sf),
Text( Text(
playerName, playerName,
style: HomeConfig.playerNameStyle, style: TextStyle(fontSize: 14 * sf, fontWeight: FontWeight.bold, color: Colors.white),
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
@@ -80,38 +88,38 @@ class StatCard extends StatelessWidget {
), ),
if (isHighlighted) if (isHighlighted)
Container( Container(
padding: EdgeInsets.all(8), padding: EdgeInsets.all(6 * sf),
decoration: BoxDecoration( decoration: const BoxDecoration(
color: Colors.amber, color: Colors.amber,
shape: BoxShape.circle, shape: BoxShape.circle,
), ),
child: Icon( child: Icon(
Icons.star, Icons.star,
size: 20, size: 16 * sf,
color: Colors.white, color: Colors.white,
), ),
), ),
], ],
), ),
SizedBox(height: 10), SizedBox(height: 8 * sf),
// Ícone // Ícone
Container( Container(
width: 60, width: 45 * sf,
height: 60, height: 45 * sf,
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2), color: Colors.white.withOpacity(0.2),
shape: BoxShape.circle, shape: BoxShape.circle,
), ),
child: Icon( child: Icon(
icon, icon,
size: 30, size: 24 * sf,
color: Colors.white, color: Colors.white,
), ),
), ),
Spacer(), const Spacer(),
// Estatística // Estatística
Center( Center(
@@ -119,26 +127,26 @@ class StatCard extends StatelessWidget {
children: [ children: [
Text( Text(
statValue, statValue,
style: HomeConfig.statValueStyle, style: TextStyle(fontSize: 34 * sf, fontWeight: FontWeight.bold, color: Colors.white),
), ),
SizedBox(height: 5), SizedBox(height: 2 * sf),
Text( Text(
statLabel.toUpperCase(), statLabel.toUpperCase(),
style: HomeConfig.statLabelStyle, style: TextStyle(fontSize: 12 * sf, color: Colors.white70),
), ),
], ],
), ),
), ),
Spacer(), const Spacer(),
// Botão // Botão
Container( Container(
width: double.infinity, width: double.infinity,
padding: EdgeInsets.symmetric(vertical: 12), padding: EdgeInsets.symmetric(vertical: 8 * sf),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2), color: Colors.white.withOpacity(0.2),
borderRadius: BorderRadius.circular(15), borderRadius: BorderRadius.circular(10 * sf),
), ),
child: Center( child: Center(
child: Text( child: Text(
@@ -146,7 +154,7 @@ class StatCard extends StatelessWidget {
style: TextStyle( style: TextStyle(
color: Colors.white, color: Colors.white,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
fontSize: 14, fontSize: 11 * sf,
letterSpacing: 1, letterSpacing: 1,
), ),
), ),
@@ -169,12 +177,12 @@ class SportGrid extends StatelessWidget {
const SportGrid({ const SportGrid({
super.key, super.key,
required this.children, required this.children,
this.spacing = HomeConfig.cardSpacing, this.spacing = 20.0, // Valor padrão se não for passado nada
}); });
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (children.isEmpty) return SizedBox(); if (children.isEmpty) return const SizedBox();
return Column( return Column(
children: [ children: [

View File

@@ -5,35 +5,48 @@ import 'package:playmaker/controllers/placar_controller.dart';
class TopScoreboard extends StatelessWidget { class TopScoreboard extends StatelessWidget {
final PlacarController controller; final PlacarController controller;
final double sf; final double sf;
const TopScoreboard({super.key, required this.controller, required this.sf}); const TopScoreboard({super.key, required this.controller, required this.sf});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return Container(
padding: EdgeInsets.symmetric(vertical: 8 * sf, horizontal: 30 * sf), padding: EdgeInsets.symmetric(vertical: 10 * sf, horizontal: 35 * sf),
decoration: BoxDecoration( decoration: BoxDecoration(
color: const Color(0xFF16202C), color: const Color(0xFF16202C),
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20 * sf), bottomRight: Radius.circular(20 * sf)), borderRadius: BorderRadius.only(
border: Border.all(color: Colors.white, width: 2 * sf), bottomLeft: Radius.circular(22 * sf),
bottomRight: Radius.circular(22 * sf)
),
border: Border.all(color: Colors.white, width: 2.5 * sf),
), ),
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
_buildTeamSection(controller.myTeam, controller.myScore, controller.myFouls, controller.myTimeoutsUsed, const Color(0xFF1E5BB2), false, sf), _buildTeamSection(controller.myTeam, controller.myScore, controller.myFouls, controller.myTimeoutsUsed, const Color(0xFF1E5BB2), false, sf),
SizedBox(width: 25 * sf), SizedBox(width: 30 * sf),
Column( Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Container( Container(
padding: EdgeInsets.symmetric(horizontal: 16 * sf, vertical: 4 * sf), padding: EdgeInsets.symmetric(horizontal: 18 * sf, vertical: 5 * sf),
decoration: BoxDecoration(color: const Color(0xFF2C3E50), borderRadius: BorderRadius.circular(8 * sf)), decoration: BoxDecoration(
child: Text(controller.formatTime(), style: TextStyle(color: Colors.white, fontSize: 26 * sf, fontWeight: FontWeight.w900, fontFamily: 'monospace', letterSpacing: 2 * sf)), color: const Color(0xFF2C3E50),
borderRadius: BorderRadius.circular(9 * sf)
),
child: Text(
controller.formatTime(),
style: TextStyle(color: Colors.white, fontSize: 28 * sf, fontWeight: FontWeight.w900, fontFamily: 'monospace', letterSpacing: 2 * sf)
),
),
SizedBox(height: 5 * sf),
Text(
"PERÍODO ${controller.currentQuarter}",
style: TextStyle(color: Colors.orangeAccent, fontSize: 14 * sf, fontWeight: FontWeight.w900)
), ),
SizedBox(height: 4 * sf),
Text("PERÍODO ${controller.currentQuarter}", style: TextStyle(color: Colors.orangeAccent, fontSize: 13 * sf, fontWeight: FontWeight.w900)),
], ],
), ),
SizedBox(width: 25 * sf), SizedBox(width: 30 * sf),
_buildTeamSection(controller.opponentTeam, controller.opponentScore, controller.opponentFouls, controller.opponentTimeoutsUsed, const Color(0xFFD92C2C), true, sf), _buildTeamSection(controller.opponentTeam, controller.opponentScore, controller.opponentFouls, controller.opponentTimeoutsUsed, const Color(0xFFD92C2C), true, sf),
], ],
), ),
@@ -41,24 +54,42 @@ class TopScoreboard extends StatelessWidget {
} }
Widget _buildTeamSection(String name, int score, int fouls, int timeouts, Color color, bool isOpp, double sf) { Widget _buildTeamSection(String name, int score, int fouls, int timeouts, Color color, bool isOpp, double sf) {
int displayFouls = fouls > 5 ? 5 : fouls;
final timeoutIndicators = Row( final timeoutIndicators = Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: List.generate(3, (index) => Container( children: List.generate(3, (index) => Container(
margin: EdgeInsets.symmetric(horizontal: 3 * sf), margin: EdgeInsets.symmetric(horizontal: 3.5 * sf),
width: 10 * sf, height: 10 * sf, width: 12 * sf, height: 12 * sf,
decoration: BoxDecoration(shape: BoxShape.circle, color: index < timeouts ? Colors.yellow : Colors.grey.shade600, border: Border.all(color: Colors.white54, width: 1.5 * sf)), decoration: BoxDecoration(
shape: BoxShape.circle,
color: index < timeouts ? Colors.yellow : Colors.grey.shade600,
border: Border.all(color: Colors.white54, width: 1.5 * sf)
),
)), )),
); );
List<Widget> content = [ List<Widget> content = [
Column(children: [_scoreBox(score, color, sf), SizedBox(height: 6 * sf), timeoutIndicators]), Column(
SizedBox(width: 15 * sf), children: [
_scoreBox(score, color, sf),
SizedBox(height: 7 * sf),
timeoutIndicators
]
),
SizedBox(width: 18 * sf),
Column( Column(
crossAxisAlignment: isOpp ? CrossAxisAlignment.start : CrossAxisAlignment.end, crossAxisAlignment: isOpp ? CrossAxisAlignment.start : CrossAxisAlignment.end,
children: [ children: [
Text(name.toUpperCase(), style: TextStyle(color: Colors.white, fontSize: 18 * sf, fontWeight: FontWeight.w900, letterSpacing: 1 * sf)), Text(
SizedBox(height: 4 * sf), name.toUpperCase(),
Text("FALTAS: $fouls", style: TextStyle(color: fouls >= 5 ? Colors.redAccent : Colors.yellowAccent, fontSize: 12 * sf, fontWeight: FontWeight.bold)), style: TextStyle(color: Colors.white, fontSize: 20 * sf, fontWeight: FontWeight.w900, letterSpacing: 1.2 * sf)
),
SizedBox(height: 5 * sf),
Text(
"FALTAS: $displayFouls",
style: TextStyle(color: displayFouls >= 5 ? Colors.redAccent : Colors.yellowAccent, fontSize: 13 * sf, fontWeight: FontWeight.bold)
),
], ],
) )
]; ];
@@ -67,10 +98,10 @@ class TopScoreboard extends StatelessWidget {
} }
Widget _scoreBox(int score, Color color, double sf) => Container( Widget _scoreBox(int score, Color color, double sf) => Container(
width: 50 * sf, height: 40 * sf, width: 58 * sf, height: 45 * sf,
alignment: Alignment.center, alignment: Alignment.center,
decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(6 * sf)), decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(7 * sf)),
child: Text(score.toString(), style: TextStyle(color: Colors.white, fontSize: 24 * sf, fontWeight: FontWeight.w900)), child: Text(score.toString(), style: TextStyle(color: Colors.white, fontSize: 26 * sf, fontWeight: FontWeight.w900)),
); );
} }
@@ -79,6 +110,7 @@ class BenchPlayersList extends StatelessWidget {
final PlacarController controller; final PlacarController controller;
final bool isOpponent; final bool isOpponent;
final double sf; final double sf;
const BenchPlayersList({super.key, required this.controller, required this.isOpponent, required this.sf}); const BenchPlayersList({super.key, required this.controller, required this.isOpponent, required this.sf});
@override @override
@@ -95,23 +127,45 @@ class BenchPlayersList extends StatelessWidget {
final bool isFouledOut = fouls >= 5; final bool isFouledOut = fouls >= 5;
Widget avatarUI = Container( Widget avatarUI = Container(
margin: EdgeInsets.only(bottom: 6 * sf), margin: EdgeInsets.only(bottom: 7 * sf),
decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: Colors.white, width: 1.5 * sf), boxShadow: [BoxShadow(color: Colors.black45, blurRadius: 4 * sf, offset: Offset(0, 2 * sf))]), decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.white, width: 1.8 * sf),
boxShadow: [BoxShadow(color: Colors.black45, blurRadius: 5 * sf, offset: Offset(0, 2.5 * sf))]
),
child: CircleAvatar( child: CircleAvatar(
radius: 20 * sf, radius: 22 * sf,
backgroundColor: isFouledOut ? Colors.grey.shade800 : teamColor, backgroundColor: isFouledOut ? Colors.grey.shade800 : teamColor,
child: Text(num, style: TextStyle(color: isFouledOut ? Colors.red.shade300 : Colors.white, fontSize: 14 * sf, fontWeight: FontWeight.bold, decoration: isFouledOut ? TextDecoration.lineThrough : TextDecoration.none)), child: Text(
num,
style: TextStyle(
color: isFouledOut ? Colors.red.shade300 : Colors.white,
fontSize: 16 * sf,
fontWeight: FontWeight.bold,
decoration: isFouledOut ? TextDecoration.lineThrough : TextDecoration.none
)
),
), ),
); );
if (isFouledOut) { if (isFouledOut) {
return GestureDetector(onTap: () => ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('🛑 $playerName não pode voltar (Expulso).'), backgroundColor: Colors.red)), child: avatarUI); return GestureDetector(
onTap: () => ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('🛑 $playerName não pode voltar (Expulso).'), backgroundColor: Colors.red)),
child: avatarUI
);
} }
return Draggable<String>( return Draggable<String>(
data: "$prefix$playerName", data: "$prefix$playerName",
feedback: Material(color: Colors.transparent, child: CircleAvatar(radius: 25 * sf, backgroundColor: teamColor, child: Text(num, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16 * sf)))), feedback: Material(
childWhenDragging: Opacity(opacity: 0.5, child: SizedBox(width: 40 * sf, height: 40 * sf)), color: Colors.transparent,
child: CircleAvatar(
radius: 28 * sf,
backgroundColor: teamColor,
child: Text(num, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18 * sf))
)
),
childWhenDragging: Opacity(opacity: 0.5, child: SizedBox(width: 45 * sf, height: 45 * sf)),
child: avatarUI, child: avatarUI,
); );
}).toList(), }).toList(),
@@ -140,17 +194,20 @@ class PlayerCourtCard extends StatelessWidget {
feedback: Material( feedback: Material(
color: Colors.transparent, color: Colors.transparent,
child: Container( child: Container(
padding: EdgeInsets.symmetric(horizontal: 16 * sf, vertical: 10 * sf), padding: EdgeInsets.symmetric(horizontal: 18 * sf, vertical: 11 * sf),
decoration: BoxDecoration(color: teamColor.withOpacity(0.9), borderRadius: BorderRadius.circular(8 * sf)), decoration: BoxDecoration(color: teamColor.withOpacity(0.9), borderRadius: BorderRadius.circular(9 * sf)),
child: Text(name, style: TextStyle(color: Colors.white, fontSize: 18 * sf, fontWeight: FontWeight.bold)), child: Text(name, style: TextStyle(color: Colors.white, fontSize: 20 * sf, fontWeight: FontWeight.bold)),
), ),
), ),
childWhenDragging: Opacity(opacity: 0.5, child: _playerCardUI(number, name, stats, teamColor, false, false, sf)), childWhenDragging: Opacity(opacity: 0.5, child: _playerCardUI(number, name, stats, teamColor, false, false, sf)),
child: DragTarget<String>( child: DragTarget<String>(
onAcceptWithDetails: (details) { onAcceptWithDetails: (details) {
final action = details.data; final action = details.data;
if (action.startsWith("add_") || action.startsWith("sub_") || action.startsWith("miss_")) controller.handleActionDrag(context, action, "$prefix$name"); if (action.startsWith("add_") || action.startsWith("sub_") || action.startsWith("miss_")) {
else if (action.startsWith("bench_")) controller.handleSubbing(context, action, name, isOpponent); controller.handleActionDrag(context, action, "$prefix$name");
} else if (action.startsWith("bench_")) {
controller.handleSubbing(context, action, name, isOpponent);
}
}, },
builder: (context, candidateData, rejectedData) { builder: (context, candidateData, rejectedData) {
bool isSubbing = candidateData.any((data) => data != null && (data.startsWith("bench_my_") || data.startsWith("bench_opp_"))); bool isSubbing = candidateData.any((data) => data != null && (data.startsWith("bench_my_") || data.startsWith("bench_opp_")));
@@ -165,8 +222,12 @@ class PlayerCourtCard extends StatelessWidget {
bool isFouledOut = stats["fls"]! >= 5; bool isFouledOut = stats["fls"]! >= 5;
Color bgColor = isFouledOut ? Colors.red.shade50 : Colors.white; Color bgColor = isFouledOut ? Colors.red.shade50 : Colors.white;
Color borderColor = isFouledOut ? Colors.redAccent : Colors.transparent; Color borderColor = isFouledOut ? Colors.redAccent : Colors.transparent;
if (isSubbing) { bgColor = Colors.blue.shade50; borderColor = Colors.blue; }
else if (isActionHover && !isFouledOut) { bgColor = Colors.orange.shade50; borderColor = Colors.orange; } if (isSubbing) {
bgColor = Colors.blue.shade50; borderColor = Colors.blue;
} else if (isActionHover && !isFouledOut) {
bgColor = Colors.orange.shade50; borderColor = Colors.orange;
}
int fgm = stats["fgm"]!; int fgm = stats["fgm"]!;
int fga = stats["fga"]!; int fga = stats["fga"]!;
@@ -176,111 +237,135 @@ class PlayerCourtCard extends StatelessWidget {
return Container( return Container(
decoration: BoxDecoration( decoration: BoxDecoration(
color: bgColor, color: bgColor,
borderRadius: BorderRadius.circular(8 * sf), borderRadius: BorderRadius.circular(11 * sf),
border: Border.all(color: borderColor, width: 2 * sf), border: Border.all(color: borderColor, width: 1.8 * sf),
boxShadow: [BoxShadow(color: Colors.black45, blurRadius: 4 * sf, offset: Offset(2 * sf, 3 * sf))], boxShadow: [BoxShadow(color: Colors.black26, blurRadius: 5 * sf, offset: Offset(2 * sf, 3.5 * sf))],
), ),
child: Row( child: ClipRRect(
mainAxisSize: MainAxisSize.min, borderRadius: BorderRadius.circular(9 * sf),
children: [ child: IntrinsicHeight(
Container( child: Row(
padding: EdgeInsets.symmetric(horizontal: 10 * sf, vertical: 12 * sf), mainAxisSize: MainAxisSize.min,
decoration: BoxDecoration(color: isFouledOut ? Colors.grey[700] : teamColor, borderRadius: BorderRadius.horizontal(left: Radius.circular(6 * sf))), crossAxisAlignment: CrossAxisAlignment.stretch,
child: Text(number, style: TextStyle(color: Colors.white, fontSize: 18 * sf, fontWeight: FontWeight.w900)), children: [
Container(
padding: EdgeInsets.symmetric(horizontal: 16 * sf),
color: isFouledOut ? Colors.grey[700] : teamColor,
alignment: Alignment.center,
child: Text(number, style: TextStyle(color: Colors.white, fontSize: 22 * sf, fontWeight: FontWeight.bold)),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 12 * sf, vertical: 7 * sf),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
displayName,
style: TextStyle(fontSize: 16 * sf, fontWeight: FontWeight.bold, color: isFouledOut ? Colors.red : Colors.black87, decoration: isFouledOut ? TextDecoration.lineThrough : TextDecoration.none)
),
SizedBox(height: 2.5 * sf),
Text(
"${stats["pts"]} Pts | FG: $fgm/$fga ($fgPercent%)",
style: TextStyle(fontSize: 12 * sf, color: isFouledOut ? Colors.red : Colors.grey[700], fontWeight: FontWeight.w600)
),
Text(
"${stats["ast"]} Ast | ${stats["orb"]! + stats["drb"]!} Rbs | ${stats["fls"]} Fls",
style: TextStyle(fontSize: 12 * sf, color: isFouledOut ? Colors.red : Colors.grey[500], fontWeight: FontWeight.w600)
),
],
),
),
],
), ),
Padding( ),
padding: EdgeInsets.symmetric(horizontal: 8 * sf, vertical: 4 * sf),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min,
children: [
Text(displayName, style: TextStyle(fontSize: 14 * sf, fontWeight: FontWeight.bold, color: isFouledOut ? Colors.red : Colors.black87, decoration: isFouledOut ? TextDecoration.lineThrough : TextDecoration.none)),
Text("${stats["pts"]} Pts | FG: $fgm/$fga ($fgPercent%)", style: TextStyle(fontSize: 10 * sf, color: isFouledOut ? Colors.red : Colors.grey[800], fontWeight: FontWeight.bold)),
Text("${stats["ast"]} Ast | ${stats["rbs"]} Rbs | ${stats["fls"]} Fls", style: TextStyle(fontSize: 10 * sf, color: isFouledOut ? Colors.red : Colors.grey[600], fontWeight: FontWeight.w600)),
],
),
),
],
), ),
); );
} }
} }
// --- PAINEL DE BOTÕES DE AÇÃO (PONTO REBUÇADO) --- // --- PAINEL DE BOTÕES DE AÇÃO ---
class ActionButtonsPanel extends StatelessWidget { class ActionButtonsPanel extends StatelessWidget {
final PlacarController controller; final PlacarController controller;
final double sf; final double sf;
const ActionButtonsPanel({super.key, required this.controller, required this.sf}); const ActionButtonsPanel({super.key, required this.controller, required this.sf});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// Aumentei ligeiramente o tamanho dos botões de ação face ao último código! final double baseSize = 65 * sf; // Reduzido (Antes era 75)
final double baseSize = 56 * sf; // Era 48 (inicialmente 65) final double feedSize = 82 * sf; // Reduzido (Antes era 95)
final double feedSize = 70 * sf; // Era 60 (inicialmente 80) final double gap = 7 * sf;
final double gap = 10 * sf;
return Row( return Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end,
children: [ children: [
_columnBtn([ _columnBtn([
_actionBtn("T.O", const Color(0xFF1E5BB2), () => controller.useTimeout(false), baseSize, feedSize, sf), _dragAndTargetBtn("M1", Colors.redAccent, "miss_1", baseSize, feedSize, sf),
_dragAndTargetBtn("1", Colors.orange, "add_pts_1", baseSize, feedSize, sf), _dragAndTargetBtn("1", Colors.orange, "add_pts_1", baseSize, feedSize, sf),
_dragAndTargetBtn("1", Colors.orange, "sub_pts_1", baseSize, feedSize, sf, isX: true), _dragAndTargetBtn("1", Colors.orange, "sub_pts_1", baseSize, feedSize, sf, isX: true),
_dragAndTargetBtn("STL", Colors.green, "add_stl", baseSize, feedSize, sf), _dragAndTargetBtn("STL", Colors.green, "add_stl", baseSize, feedSize, sf),
], gap), ], gap),
SizedBox(width: gap * 2), SizedBox(width: gap * 1),
_columnBtn([ _columnBtn([
_dragAndTargetBtn("M2", Colors.redAccent, "miss_2", baseSize, feedSize, sf), _dragAndTargetBtn("M2", Colors.redAccent, "miss_2", baseSize, feedSize, sf),
_dragAndTargetBtn("2", Colors.orange, "add_pts_2", baseSize, feedSize, sf), _dragAndTargetBtn("2", Colors.orange, "add_pts_2", baseSize, feedSize, sf),
_dragAndTargetBtn("2", Colors.orange, "sub_pts_2", baseSize, feedSize, sf, isX: true), _dragAndTargetBtn("2", Colors.orange, "sub_pts_2", baseSize, feedSize, sf, isX: true),
_dragAndTargetBtn("AST", Colors.blueGrey, "add_ast", baseSize, feedSize, sf), _dragAndTargetBtn("AST", Colors.blueGrey, "add_ast", baseSize, feedSize, sf),
], gap), ], gap),
SizedBox(width: gap * 2), SizedBox(width: gap * 1),
_columnBtn([ _columnBtn([
_dragAndTargetBtn("M3", Colors.redAccent, "miss_3", baseSize, feedSize, sf), _dragAndTargetBtn("M3", Colors.redAccent, "miss_3", baseSize, feedSize, sf),
_dragAndTargetBtn("3", Colors.orange, "add_pts_3", baseSize, feedSize, sf), _dragAndTargetBtn("3", Colors.orange, "add_pts_3", baseSize, feedSize, sf),
_dragAndTargetBtn("3", Colors.orange, "sub_pts_3", baseSize, feedSize, sf, isX: true), _dragAndTargetBtn("3", Colors.orange, "sub_pts_3", baseSize, feedSize, sf, isX: true),
_dragAndTargetBtn("TOV", Colors.redAccent, "add_tov", baseSize, feedSize, sf), _dragAndTargetBtn("TOV", Colors.redAccent, "add_tov", baseSize, feedSize, sf),
], gap), ], gap),
SizedBox(width: gap * 2), SizedBox(width: gap * 1),
_columnBtn([ _columnBtn([
_actionBtn("T.O", const Color(0xFFD92C2C), () => controller.useTimeout(true), baseSize, feedSize, sf), _dragAndTargetBtn("ORB", const Color(0xFF1E2A38), "add_orb", baseSize, feedSize, sf, icon: Icons.sports_basketball),
_dragAndTargetBtn("ORB", const Color(0xFF1E2A38), "add_rbs", baseSize, feedSize, sf, icon: Icons.sports_basketball), _dragAndTargetBtn("DRB", const Color(0xFF1E2A38), "add_drb", baseSize, feedSize, sf, icon: Icons.sports_basketball),
_dragAndTargetBtn("DRB", const Color(0xFF1E2A38), "add_rbs", baseSize, feedSize, sf, icon: Icons.sports_basketball),
_dragAndTargetBtn("BLK", Colors.deepPurple, "add_blk", baseSize, feedSize, sf, icon: Icons.front_hand), _dragAndTargetBtn("BLK", Colors.deepPurple, "add_blk", baseSize, feedSize, sf, icon: Icons.front_hand),
], gap), ], gap),
], ],
); );
} }
Widget _columnBtn(List<Widget> children, double gap) => Column(mainAxisSize: MainAxisSize.min, children: children.map((c) => Padding(padding: EdgeInsets.only(bottom: gap), child: c)).toList()); Widget _columnBtn(List<Widget> children, double gap) {
return Column(
mainAxisSize: MainAxisSize.min,
children: children.map((c) => Padding(padding: EdgeInsets.only(bottom: gap), child: c)).toList()
);
}
Widget _dragAndTargetBtn(String label, Color color, String actionData, double baseSize, double feedSize, double sf, {IconData? icon, bool isX = false}) { Widget _dragAndTargetBtn(String label, Color color, String actionData, double baseSize, double feedSize, double sf, {IconData? icon, bool isX = false}) {
return Draggable<String>( return Draggable<String>(
data: actionData, data: actionData,
feedback: _circle(label, color, icon, true, baseSize, feedSize, sf, isX: isX), feedback: _circle(label, color, icon, true, baseSize, feedSize, sf, isX: isX),
childWhenDragging: Opacity(opacity: 0.5, child: _circle(label, color, icon, false, baseSize, feedSize, sf, isX: isX)), childWhenDragging: Opacity(
opacity: 0.5,
child: _circle(label, color, icon, false, baseSize, feedSize, sf, isX: isX)
),
child: DragTarget<String>( child: DragTarget<String>(
onAcceptWithDetails: (details) {}, onAcceptWithDetails: (details) {},
builder: (context, candidateData, rejectedData) { builder: (context, candidateData, rejectedData) {
bool isHovered = candidateData.any((data) => data != null && data.startsWith("player_")); bool isHovered = candidateData.any((data) => data != null && data.startsWith("player_"));
return Transform.scale( return Transform.scale(
scale: isHovered ? 1.15 : 1.0, scale: isHovered ? 1.15 : 1.0,
child: Container(decoration: isHovered ? BoxDecoration(shape: BoxShape.circle, boxShadow: [BoxShadow(color: Colors.white, blurRadius: 10 * sf, spreadRadius: 3 * sf)]) : null, child: _circle(label, color, icon, false, baseSize, feedSize, sf, isX: isX)), child: Container(
decoration: isHovered ? BoxDecoration(shape: BoxShape.circle, boxShadow: [BoxShadow(color: Colors.white, blurRadius: 10 * sf, spreadRadius: 3 * sf)]) : null,
child: _circle(label, color, icon, false, baseSize, feedSize, sf, isX: isX)
),
); );
} }
), ),
); );
} }
Widget _actionBtn(String label, Color color, VoidCallback onTap, double baseSize, double feedSize, double sf, {IconData? icon, bool isX = false}) {
return GestureDetector(onTap: onTap, child: _circle(label, color, icon, false, baseSize, feedSize, sf, isX: isX));
}
Widget _circle(String label, Color color, IconData? icon, bool isFeed, double baseSize, double feedSize, double sf, {bool isX = false}) { Widget _circle(String label, Color color, IconData? icon, bool isFeed, double baseSize, double feedSize, double sf, {bool isX = false}) {
double size = isFeed ? feedSize : baseSize; double size = isFeed ? feedSize : baseSize;
Widget content; Widget content;
bool isPointBtn = label == "1" || label == "2" || label == "3" || label == "M2" || label == "M3"; bool isPointBtn = label == "1" || label == "2" || label == "3" || label == "M1" || label == "M2" || label == "M3";
bool isBlkBtn = label == "BLK"; bool isBlkBtn = label == "BLK";
if (isPointBtn) { if (isPointBtn) {
@@ -297,8 +382,7 @@ class ActionButtonsPanel extends StatelessWidget {
), ),
], ],
); );
} } else if (isBlkBtn) {
else if (isBlkBtn) {
content = Stack( content = Stack(
alignment: Alignment.center, alignment: Alignment.center,
children: [ children: [
@@ -319,12 +403,14 @@ class ActionButtonsPanel extends StatelessWidget {
} }
return Stack( return Stack(
clipBehavior: Clip.none, alignment: Alignment.bottomRight, clipBehavior: Clip.none,
alignment: Alignment.bottomRight,
children: [ children: [
Container( Container(
width: size, height: size, width: size, height: size,
decoration: (isPointBtn || isBlkBtn) ? const BoxDecoration(color: Colors.transparent) : BoxDecoration(gradient: RadialGradient(colors: [color.withOpacity(0.7), color], radius: 0.8), shape: BoxShape.circle, boxShadow: [BoxShadow(color: Colors.black38, blurRadius: 6 * sf, offset: Offset(0, 3 * sf))]), decoration: (isPointBtn || isBlkBtn) ? const BoxDecoration(color: Colors.transparent) : BoxDecoration(gradient: RadialGradient(colors: [color.withOpacity(0.7), color], radius: 0.8), shape: BoxShape.circle, boxShadow: [BoxShadow(color: Colors.black38, blurRadius: 6 * sf, offset: Offset(0, 3 * sf))]),
alignment: Alignment.center, child: content, alignment: Alignment.center,
child: content,
), ),
if (isX) Positioned(top: 0, right: 0, child: Container(decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), child: Icon(Icons.cancel, color: Colors.red, size: size * 0.4))), if (isX) Positioned(top: 0, right: 0, child: Container(decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), child: Icon(Icons.cancel, color: Colors.red, size: size * 0.4))),
], ],

View File

@@ -7,12 +7,14 @@ class TeamCard extends StatelessWidget {
final Team team; final Team team;
final TeamController controller; final TeamController controller;
final VoidCallback onFavoriteTap; final VoidCallback onFavoriteTap;
final double sf; // <-- Variável de escala
const TeamCard({ const TeamCard({
super.key, super.key,
required this.team, required this.team,
required this.controller, required this.controller,
required this.onFavoriteTap, required this.onFavoriteTap,
required this.sf,
}); });
@override @override
@@ -20,17 +22,17 @@ class TeamCard extends StatelessWidget {
return Card( return Card(
color: Colors.white, color: Colors.white,
elevation: 3, elevation: 3,
margin: const EdgeInsets.only(bottom: 12), margin: EdgeInsets.only(bottom: 12 * sf),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15 * sf)),
child: ListTile( child: ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), contentPadding: EdgeInsets.symmetric(horizontal: 16 * sf, vertical: 8 * sf),
// --- 1. IMAGEM + FAVORITO --- // --- 1. IMAGEM + FAVORITO ---
leading: Stack( leading: Stack(
clipBehavior: Clip.none, clipBehavior: Clip.none,
children: [ children: [
CircleAvatar( CircleAvatar(
radius: 28, radius: 28 * sf,
backgroundColor: Colors.grey[200], backgroundColor: Colors.grey[200],
backgroundImage: (team.imageUrl.isNotEmpty && team.imageUrl.startsWith('http')) backgroundImage: (team.imageUrl.isNotEmpty && team.imageUrl.startsWith('http'))
? NetworkImage(team.imageUrl) ? NetworkImage(team.imageUrl)
@@ -38,22 +40,22 @@ class TeamCard extends StatelessWidget {
child: (team.imageUrl.isEmpty || !team.imageUrl.startsWith('http')) child: (team.imageUrl.isEmpty || !team.imageUrl.startsWith('http'))
? Text( ? Text(
team.imageUrl.isEmpty ? "🏀" : team.imageUrl, team.imageUrl.isEmpty ? "🏀" : team.imageUrl,
style: const TextStyle(fontSize: 24), style: TextStyle(fontSize: 24 * sf),
) )
: null, : null,
), ),
Positioned( Positioned(
left: -15, left: -15 * sf,
top: -10, top: -10 * sf,
child: IconButton( child: IconButton(
icon: Icon( icon: Icon(
team.isFavorite ? Icons.star : Icons.star_border, team.isFavorite ? Icons.star : Icons.star_border,
color: team.isFavorite ? Colors.amber : Colors.black.withOpacity(0.1), color: team.isFavorite ? Colors.amber : Colors.black.withOpacity(0.1),
size: 28, size: 28 * sf,
shadows: [ shadows: [
Shadow( Shadow(
color: Colors.black.withOpacity(team.isFavorite ? 0.3 : 0.1), color: Colors.black.withOpacity(team.isFavorite ? 0.3 : 0.1),
blurRadius: 4, blurRadius: 4 * sf,
), ),
], ],
), ),
@@ -66,89 +68,89 @@ class TeamCard extends StatelessWidget {
// --- 2. TÍTULO --- // --- 2. TÍTULO ---
title: Text( title: Text(
team.name, team.name,
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16 * sf),
overflow: TextOverflow.ellipsis, // Previne overflows em nomes longos
), ),
// --- 3. SUBTÍTULO (Contagem + Época) --- // --- 3. SUBTÍTULO (Contagem + Época) ---
subtitle: Padding( subtitle: Padding(
padding: const EdgeInsets.only(top: 6.0), padding: EdgeInsets.only(top: 6.0 * sf),
child: Row( child: Row(
children: [ children: [
const Icon(Icons.groups_outlined, size: 16, color: Colors.grey), Icon(Icons.groups_outlined, size: 16 * sf, color: Colors.grey),
const SizedBox(width: 4), SizedBox(width: 4 * sf),
FutureBuilder<int>( FutureBuilder<int>(
future: controller.getPlayerCount(team.id), future: controller.getPlayerCount(team.id),
initialData: 0, initialData: 0,
builder: (context, snapshot) { builder: (context, snapshot) {
final count = snapshot.data ?? 0; final count = snapshot.data ?? 0;
return Text( return Text(
"$count Jogadores", "$count Jogs.", // Abreviado para poupar espaço
style: TextStyle( style: TextStyle(
color: count > 0 ? Colors.green[700] : Colors.orange, color: count > 0 ? Colors.green[700] : Colors.orange,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
fontSize: 13, fontSize: 13 * sf,
), ),
); );
}, },
), ),
const SizedBox(width: 10), SizedBox(width: 8 * sf),
Text( Expanded( // Garante que a temporada se adapta se faltar espaço
"| ${team.season}", child: Text(
style: const TextStyle(color: Colors.grey, fontSize: 13), "| ${team.season}",
style: TextStyle(color: Colors.grey, fontSize: 13 * sf),
overflow: TextOverflow.ellipsis,
),
), ),
], ],
), ),
), ),
// --- 4. BOTÕES (Estatísticas e Apagar) --- // --- 4. BOTÕES (Estatísticas e Apagar) ---
trailing: SizedBox( // Removido o SizedBox fixo! Agora é MainAxisSize.min
width: 96, // Aumentei um pouco para caberem bem os dois botões trailing: Row(
child: Row( mainAxisSize: MainAxisSize.min, // <-- ISTO RESOLVE O OVERFLOW DAS RISCAS AMARELAS
mainAxisAlignment: MainAxisAlignment.end, children: [
children: [ IconButton(
IconButton( tooltip: 'Ver Estatísticas',
tooltip: 'Ver Estatísticas', icon: Icon(Icons.bar_chart_rounded, color: Colors.blue, size: 24 * sf),
icon: const Icon(Icons.bar_chart_rounded, color: Colors.blue), onPressed: () {
onPressed: () { Navigator.push(
// CORRIGIDO: Agora chama a classe TeamStatsPage corretamente context,
Navigator.push( MaterialPageRoute(
context, builder: (context) => TeamStatsPage(team: team),
MaterialPageRoute( ),
builder: (context) => TeamStatsPage(team: team), );
), },
); ),
}, IconButton(
), tooltip: 'Eliminar Equipa',
IconButton( icon: Icon(Icons.delete_outline, color: const Color(0xFFE74C3C), size: 24 * sf),
tooltip: 'Eliminar Equipa', onPressed: () => _confirmDelete(context),
icon: const Icon(Icons.delete_outline, color: Color(0xFFE74C3C)), ),
onPressed: () => _confirmDelete(context), ],
),
],
),
), ),
), ),
); );
} }
// Função de confirmação de exclusão
void _confirmDelete(BuildContext context) { void _confirmDelete(BuildContext context) {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: const Text('Eliminar Equipa?'), title: Text('Eliminar Equipa?', style: TextStyle(fontSize: 18 * sf, fontWeight: FontWeight.bold)),
content: Text('Tens a certeza que queres eliminar "${team.name}"?'), content: Text('Tens a certeza que queres eliminar "${team.name}"?', style: TextStyle(fontSize: 14 * sf)),
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
child: const Text('Cancelar'), child: Text('Cancelar', style: TextStyle(fontSize: 14 * sf)),
), ),
TextButton( TextButton(
onPressed: () { onPressed: () {
controller.deleteTeam(team.id); controller.deleteTeam(team.id);
Navigator.pop(context); Navigator.pop(context);
}, },
child: const Text('Eliminar', style: TextStyle(color: Colors.red)), child: Text('Eliminar', style: TextStyle(color: Colors.red, fontSize: 14 * sf)),
), ),
], ],
), ),
@@ -159,8 +161,9 @@ class TeamCard extends StatelessWidget {
// --- DIALOG DE CRIAÇÃO --- // --- DIALOG DE CRIAÇÃO ---
class CreateTeamDialog extends StatefulWidget { class CreateTeamDialog extends StatefulWidget {
final Function(String name, String season, String imageUrl) onConfirm; final Function(String name, String season, String imageUrl) onConfirm;
final double sf; // Recebe a escala
const CreateTeamDialog({super.key, required this.onConfirm}); const CreateTeamDialog({super.key, required this.onConfirm, required this.sf});
@override @override
State<CreateTeamDialog> createState() => _CreateTeamDialogState(); State<CreateTeamDialog> createState() => _CreateTeamDialogState();
@@ -174,40 +177,58 @@ class _CreateTeamDialogState extends State<CreateTeamDialog> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return AlertDialog( return AlertDialog(
title: const Text('Nova Equipa'), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15 * widget.sf)),
title: Text('Nova Equipa', style: TextStyle(fontSize: 18 * widget.sf, fontWeight: FontWeight.bold)),
content: SingleChildScrollView( content: SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
TextField( TextField(
controller: _nameController, controller: _nameController,
decoration: const InputDecoration(labelText: 'Nome da Equipa'), style: TextStyle(fontSize: 14 * widget.sf),
decoration: InputDecoration(
labelText: 'Nome da Equipa',
labelStyle: TextStyle(fontSize: 14 * widget.sf)
),
textCapitalization: TextCapitalization.words, textCapitalization: TextCapitalization.words,
), ),
const SizedBox(height: 15), SizedBox(height: 15 * widget.sf),
DropdownButtonFormField<String>( DropdownButtonFormField<String>(
value: _selectedSeason, value: _selectedSeason,
decoration: const InputDecoration(labelText: 'Temporada'), decoration: InputDecoration(
labelText: 'Temporada',
labelStyle: TextStyle(fontSize: 14 * widget.sf)
),
style: TextStyle(fontSize: 14 * widget.sf, color: Colors.black87),
items: ['2023/24', '2024/25', '2025/26'] items: ['2023/24', '2024/25', '2025/26']
.map((s) => DropdownMenuItem(value: s, child: Text(s))) .map((s) => DropdownMenuItem(value: s, child: Text(s)))
.toList(), .toList(),
onChanged: (val) => setState(() => _selectedSeason = val!), onChanged: (val) => setState(() => _selectedSeason = val!),
), ),
const SizedBox(height: 15), SizedBox(height: 15 * widget.sf),
TextField( TextField(
controller: _imageController, controller: _imageController,
decoration: const InputDecoration( style: TextStyle(fontSize: 14 * widget.sf),
decoration: InputDecoration(
labelText: 'URL Imagem ou Emoji', labelText: 'URL Imagem ou Emoji',
labelStyle: TextStyle(fontSize: 14 * widget.sf),
hintText: 'Ex: 🏀 ou https://...', hintText: 'Ex: 🏀 ou https://...',
hintStyle: TextStyle(fontSize: 14 * widget.sf)
), ),
), ),
], ],
), ),
), ),
actions: [ actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancelar')), TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Cancelar', style: TextStyle(fontSize: 14 * widget.sf))
),
ElevatedButton( ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFFE74C3C)), style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFFE74C3C),
padding: EdgeInsets.symmetric(horizontal: 16 * widget.sf, vertical: 10 * widget.sf)
),
onPressed: () { onPressed: () {
if (_nameController.text.trim().isNotEmpty) { if (_nameController.text.trim().isNotEmpty) {
widget.onConfirm( widget.onConfirm(
@@ -218,7 +239,7 @@ class _CreateTeamDialogState extends State<CreateTeamDialog> {
Navigator.pop(context); Navigator.pop(context);
} }
}, },
child: const Text('Criar', style: TextStyle(color: Colors.white)), child: Text('Criar', style: TextStyle(color: Colors.white, fontSize: 14 * widget.sf)),
), ),
], ],
); );