Skip to main content

fuzo_soccer_board 0.5.0 copy "fuzo_soccer_board: ^0.5.0" to clipboard
fuzo_soccer_board: ^0.5.0 copied to clipboard

Flutter widget for a tactical soccer/football board with drag-and-drop player positioning, tactical zones, field orientation (portrait/landscape), and read-only mode. Perfect for lineup and formation editors.

example/lib/main.dart

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fuzo_soccer_board/fuzo_soccer_board.dart';

// En web usa localStorage del navegador; en móvil/desktop usa SharedPreferences.
import 'storage_io.dart' if (dart.library.html) 'storage_web.dart' as storage;

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // Configurar orientación landscape para móviles
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight,
  ]);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Soccer Board Example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
        useMaterial3: true,
      ),
      home: const SoccerBoardExample(),
    );
  }
}

class SoccerBoardExample extends StatefulWidget {
  const SoccerBoardExample({super.key});

  @override
  State<SoccerBoardExample> createState() => _SoccerBoardExampleState();
}

class _SoccerBoardExampleState extends State<SoccerBoardExample> {
  static const _storageKey = 'soccer_board_players';

  FieldOrientation _orientation = FieldOrientation.landscape;
  FieldSideFilter _sideFilter = FieldSideFilter.both;
  bool _showTacticalZones = false;
  bool _showFormationIndicator = false;
  FieldDesign _fieldDesign = FieldDesign.stripes;
  PlayerShape _playerShape = PlayerShape.card;
  bool _showOnlyFieldPlayers = false;
  bool _readOnly = false;
  int _maxPlayersPerSide = 7;
  final SidebarPosition _sidebarPosition = SidebarPosition.auto;
  /// Si true, se muestra la barra de controles; si false, el soccer board ocupa toda la pantalla.
  bool _showControls = true;
  List<Player> _players = [];
  List<Player> _availablePlayers = [];
  String? _lastTappedPlayerId;
  DateTime? _lastTappedTime;
  Timer? _tapTimer;
  static const _doubleTapDelay = 300;

  void _onPlayerTap(Player player) {
    final now = DateTime.now();
    final isDoubleTap =
        _lastTappedPlayerId == player.id &&
        _lastTappedTime != null &&
        now.difference(_lastTappedTime!).inMilliseconds < _doubleTapDelay;

    _tapTimer?.cancel();
    _tapTimer = null;

    if (isDoubleTap) {
      _lastTappedPlayerId = null;
      _lastTappedTime = null;
      if (mounted) {
        setState(() {
          _players = _players.map((p) {
            if (p.id == player.id) return p.removeFromField();
            return p;
          }).toList();
        });
      }
      return;
    }

    _lastTappedPlayerId = player.id;
    _lastTappedTime = now;
    _tapTimer = Timer(const Duration(milliseconds: _doubleTapDelay), () {
      _tapTimer = null;
      _lastTappedPlayerId = null;
      _lastTappedTime = null;
      if (!mounted) return;
      final list = _players.where((p) => p.id == player.id).toList();
      if (list.isNotEmpty) _showPlayerBottomSheet(list.first);
    });
  }

  void _showPlayerBottomSheet(Player player) {
    if (!mounted) return;
    showModalBottomSheet<void>(
      context: context,
      builder: (context) => SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text(
                player.name,
                style: Theme.of(
                  context,
                ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 8),
              if (player.number != null)
                Padding(
                  padding: const EdgeInsets.only(bottom: 4.0),
                  child: Text(
                    'Número: ${player.number}',
                    style: Theme.of(context).textTheme.bodyLarge,
                  ),
                ),
              Padding(
                padding: const EdgeInsets.only(bottom: 4.0),
                child: Text(
                  'Posición: ${player.fieldPosition ?? player.preferredPosition ?? "—"}',
                  style: Theme.of(context).textTheme.bodyLarge,
                ),
              ),
              if (player.isOnField) ...[
                const SizedBox(height: 16),
                FilledButton.icon(
                  onPressed: () {
                    if (!mounted) return;
                    setState(() {
                      _players = _players.map((p) {
                        if (p.id == player.id) {
                          return p.removeFromField();
                        }
                        return p;
                      }).toList();
                    });
                    if (context.mounted) Navigator.pop(context);
                  },
                  icon: const Icon(Icons.person_off_outlined),
                  label: const Text('Quitar del campo'),
                  style: FilledButton.styleFrom(
                    backgroundColor: Theme.of(context).colorScheme.error,
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _initializePlayers();
    _loadFromStorage();
  }

  @override
  void dispose() {
    _tapTimer?.cancel();
    super.dispose();
  }

  /// Carga jugadores desde localStorage. Si hay datos guardados, los usa y el
  /// soccer board los renderiza (los que tengan fieldX/fieldY/side en el campo).
  Future<void> _loadFromStorage() async {
    try {
      final jsonString = await storage.storageGetString(_storageKey);
      if (jsonString == null || jsonString.isEmpty) return;

      final list = jsonDecode(jsonString) as List<dynamic>;
      final loaded = list
          .map((e) => Player.fromJson(e as Map<String, dynamic>))
          .toList();
      if (loaded.isEmpty) return;

      if (mounted) setState(() => _players = loaded);
    } catch (_) {}
  }

  /// Guarda la lista actual de jugadores (y sus posiciones) en localStorage.
  Future<void> _saveToStorage() async {
    try {
      final list = _players.map((p) => p.toJson()).toList();
      final jsonString = jsonEncode(list);
      await storage.storageSetString(_storageKey, jsonString);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Guardado en localStorage')),
        );
      }
    } catch (e, st) {
      debugPrint('_saveToStorage error: $e\n$st');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              'Error al guardar: ${e.toString().split('\n').first}',
            ),
            duration: const Duration(seconds: 5),
          ),
        );
      }
    }
  }

  void _initializePlayers() {
    _availablePlayers = [
      Player(
        id: '1',
        name: 'Lionel Messi',
        number: 10,
        preferredPosition: 'RW',
      ),
      Player(
        id: '2',
        name: 'Cristiano Ronaldo',
        number: 7,
        preferredPosition: 'ST',
      ),
      Player(
        id: '3',
        name: 'Kylian Mbappé',
        number: 9,
        preferredPosition: 'LW',
      ),
      Player(
        id: '4',
        name: 'Kevin De Bruyne',
        number: 17,
        preferredPosition: 'CM',
      ),
      Player(
        id: '5',
        name: 'Virgil van Dijk',
        number: 4,
        preferredPosition: 'CB',
      ),
      Player(id: '6', name: 'Manuel Neuer', number: 1, preferredPosition: 'GK'),
      Player(id: '7', name: 'Luka Modrić', number: 10, preferredPosition: 'CM'),
      Player(
        id: '8',
        name: 'Robert Lewandowski',
        number: 9,
        preferredPosition: 'ST',
      ),
      Player(
        id: '9',
        name: 'Erling Haaland',
        number: 9,
        preferredPosition: 'ST',
      ),
      Player(id: '10', name: 'Harry Kane', number: 9, preferredPosition: 'ST'),
      Player(
        id: '11',
        name: 'Kylian Mbappé',
        number: 9,
        preferredPosition: 'ST',
      ),
      Player(
        id: '12',
        name: 'Kevin De Bruyne',
        number: 9,
        preferredPosition: 'CM',
      ),
      Player(
        id: '13',
        name: 'Virgil van Dijk',
        number: 9,
        preferredPosition: 'CB',
      ),
      Player(
        id: '14',
        name: 'Manuel Neuer',
        number: 9,
        preferredPosition: 'GK',
      ),
      Player(id: '15', name: 'Luka Modrić', number: 9, preferredPosition: 'CM'),
      Player(
        id: '16',
        name: 'Robert Lewandowski',
        number: 9,
        preferredPosition: 'ST',
      ),
      Player(
        id: '17',
        name: 'Erling Haaland',
        number: 9,
        preferredPosition: 'ST',
      ),
      Player(id: '18', name: 'Harry Kane', number: 9, preferredPosition: 'ST'),
      Player(
        id: '19',
        name: 'Kylian Mbappé',
        number: 9,
        preferredPosition: 'ST',
      ),
      Player(
        id: '20',
        name: 'Kevin De Bruyne',
        number: 9,
        preferredPosition: 'CM',
      ),
      Player(
        id: '21',
        name: 'Virgil van Dijk',
        number: 9,
        preferredPosition: 'CB',
      ),
      Player(
        id: '22',
        name: 'Manuel Neuer',
        number: 9,
        preferredPosition: 'GK',
      ),
    ];
    _players = List.from(_availablePlayers);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // Controles (ocultables con FAB para que el board ocupe toda la pantalla)
          if (_showControls)
            Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 12.0,
                vertical: 8.0,
              ),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
              ),
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // Control: Mostrar HOME/AWAY/Both
                  const Text(
                    'Lado:',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(width: 8),
                  SegmentedButton<FieldSideFilter>(
                    segments: const [
                      ButtonSegment<FieldSideFilter>(
                        value: FieldSideFilter.both,
                        label: Text('Ambos', style: TextStyle(fontSize: 11)),
                      ),
                      ButtonSegment<FieldSideFilter>(
                        value: FieldSideFilter.home,
                        label: Text('HOME', style: TextStyle(fontSize: 11)),
                      ),
                      ButtonSegment<FieldSideFilter>(
                        value: FieldSideFilter.away,
                        label: Text('AWAY', style: TextStyle(fontSize: 11)),
                      ),
                    ],
                    selected: {_sideFilter},
                    onSelectionChanged: (Set<FieldSideFilter> selection) {
                      setState(() {
                        _sideFilter = selection.first;
                      });
                    },
                  ),
                  const SizedBox(width: 16),
                  // Control: Orientación
                  const Text(
                    'Orientación:',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(width: 8),
                  SegmentedButton<FieldOrientation>(
                    segments: const [
                      ButtonSegment<FieldOrientation>(
                        value: FieldOrientation.portrait,
                        label: Text('Portrait', style: TextStyle(fontSize: 11)),
                      ),
                      ButtonSegment<FieldOrientation>(
                        value: FieldOrientation.landscape,
                        label: Text(
                          'Landscape',
                          style: TextStyle(fontSize: 11),
                        ),
                      ),
                    ],
                    selected: {_orientation},
                  onSelectionChanged: (Set<FieldOrientation> selection) {
                    final newOrientation = selection.first;
                    if (newOrientation == _orientation) return;
                    final oldOrientation = _orientation;
                    setState(() {
                      _orientation = newOrientation;
                      _players = _players.map((p) {
                        if (!p.isOnField) return p;
                        final newCoords = CoordinateConverter.convertFieldPositionToOrientation(
                          fieldX: p.fieldX!,
                          fieldY: p.fieldY!,
                          side: p.side!,
                          from: oldOrientation,
                          to: newOrientation,
                        );
                        final position = PositionDetector.detectPosition(
                          fieldX: newCoords[0],
                          fieldY: newCoords[1],
                          side: p.side!,
                          orientation: newOrientation,
                        );
                        return p.copyWith(
                          fieldX: newCoords[0],
                          fieldY: newCoords[1],
                          fieldPosition: position,
                        );
                      }).toList();
                    });
                  },
                  ),
                  const SizedBox(width: 16),
                  // Control: Mostrar posiciones tácticas
                  const Text(
                    'Posiciones:',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(width: 8),
                  Switch(
                    value: _showTacticalZones,
                    onChanged: (value) {
                      setState(() {
                        _showTacticalZones = value;
                      });
                    },
                  ),
                  const SizedBox(width: 16),
                  const Text(
                    'Diseño:',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(width: 4),
                  DropdownButton<FieldDesign>(
                    value: _fieldDesign,
                    isDense: true,
                    items: FieldDesign.values.map((d) {
                      return DropdownMenuItem<FieldDesign>(
                        value: d,
                        child: Text('Rayas alternadas', style: const TextStyle(fontSize: 12)),
                      );
                    }).toList(),
                    onChanged: (value) {
                      if (value != null) setState(() => _fieldDesign = value);
                    },
                  ),
                  const SizedBox(width: 16),
                  const Text(
                    'Jugador:',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(width: 4),
                  DropdownButton<PlayerShape>(
                    value: _playerShape,
                    isDense: true,
                    items: PlayerShape.values.map((s) {
                      final labels = {
                        PlayerShape.card: 'Tarjeta',
                        PlayerShape.circular: 'Circular',
                      };
                      return DropdownMenuItem<PlayerShape>(
                        value: s,
                        child: Text(labels[s] ?? s.name, style: const TextStyle(fontSize: 12)),
                      );
                    }).toList(),
                    onChanged: (value) {
                      if (value != null) setState(() => _playerShape = value);
                    },
                  ),
                  const SizedBox(width: 16),
                  const Text(
                    'Formación:',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(width: 8),
                  Switch(
                    value: _showFormationIndicator,
                    onChanged: (value) {
                      setState(() => _showFormationIndicator = value);
                    },
                  ),
                  const SizedBox(width: 16),
                  // Solo jugadores en cancha (oculta sidebar)
                  const Text(
                    'Solo cancha:',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(width: 8),
                  Switch(
                    value: _showOnlyFieldPlayers,
                    onChanged: (value) {
                      setState(() => _showOnlyFieldPlayers = value);
                    },
                  ),
                  const SizedBox(width: 16),
                  const Text(
                    'Solo lectura:',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(width: 8),
                  Switch(
                    value: _readOnly,
                    onChanged: (value) => setState(() => _readOnly = value),
                  ),
                  const SizedBox(width: 16),
                  const Text(
                    'Jug./lado:',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(width: 4),
                  DropdownButton<int>(
                    value: _maxPlayersPerSide,
                    isDense: true,
                    items: List.generate(11, (i) => i + 1).map((n) {
                      return DropdownMenuItem<int>(
                        value: n,
                        child: Text('$n', style: const TextStyle(fontSize: 12)),
                      );
                    }).toList(),
                    onChanged: (value) {
                      if (value != null) {
                        setState(() => _maxPlayersPerSide = value);
                      }
                    },
                  ),
                  const SizedBox(width: 16),
                  FilledButton.icon(
                    onPressed: _saveToStorage,
                    icon: const Icon(Icons.save, size: 18),
                    label: const Text(
                      'Guardar',
                      style: TextStyle(fontSize: 12),
                    ),
                  ),
                ],
              ),
            ),
          ),
          // Campo: sin padding cuando controles ocultos para que ocupe toda la pantalla.
          // En portrait se usa menos padding vertical para que la cancha no tenga espacio arriba.
          Expanded(
            child: Padding(
              padding: _showControls
                  ? (MediaQuery.orientationOf(context) == Orientation.portrait
                      ? const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0)
                      : const EdgeInsets.symmetric(horizontal: 8.0, vertical: 16.0))
                  : EdgeInsets.zero,
              child: SoccerBoardWrapper(
                orientation: _orientation,
                players: _players,
                sidebarPosition: _sidebarPosition,
                sideFilter: _sideFilter,
                showTacticalZones: _showTacticalZones,
                showFormationIndicator: _showFormationIndicator,
                showTeamNames: true,
                homeTeamName: 'Club Local',
                awayTeamName: 'Club Visitante',
                homeFormation: _showFormationIndicator
                    ? FormationHelper.fromPlayers(
                        _players.where((p) => p.side == TeamSide.home && p.isOnField).toList())
                    : null,
                awayFormation: _showFormationIndicator
                    ? FormationHelper.fromPlayers(
                        _players.where((p) => p.side == TeamSide.away && p.isOnField).toList())
                    : null,
                fieldDesign: _fieldDesign,
                playerShape: _playerShape,
                showOnlyFieldPlayers: _showOnlyFieldPlayers,
                readOnly: _readOnly,
                maxPlayersPerSide: _maxPlayersPerSide,
                onPlayerTap: _onPlayerTap,
                onPlayerPositioned: (playerId, fieldX, fieldY, side, position) {
                  setState(() {
                    _players = _players.map((p) {
                      if (p.id == playerId) {
                        return p.positionOnField(
                          x: fieldX,
                          y: fieldY,
                          side: side,
                          position: position,
                        );
                      }
                      return p;
                    }).toList();
                  });
                },
                onPlayerRemoved: (playerId) {
                  setState(() {
                    _players = _players.map((p) {
                      if (p.id == playerId) {
                        return p.removeFromField();
                      }
                      return p;
                    }).toList();
                  });
                },
                onSidebarReset: () {
                  setState(() {
                    _players = _players.map((p) => p.removeFromField()).toList();
                  });
                },
                onSidebarSave: _saveToStorage,
                onSidebarPublish: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Publicar: callback recibido')),
                  );
                },
              ),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => setState(() => _showControls = !_showControls),
        tooltip: _showControls ? 'Ocultar controles (pantalla completa)' : 'Mostrar controles',
        child: Icon(_showControls ? Icons.fullscreen : Icons.tune),
      ),
    );
  }
}
0
likes
140
points
35
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Flutter widget for a tactical soccer/football board with drag-and-drop player positioning, tactical zones, field orientation (portrait/landscape), and read-only mode. Perfect for lineup and formation editors.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

flutter

More

Packages that depend on fuzo_soccer_board