After retreving the stored data from the server, when i clicked the ckeckbox in one of the tasksk it gave the following error:

══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following RangeError was thrown while handling a gesture:
Value not in range: -1

When the exception was thrown, this was the stack

Handler: "onTap"
Recognizer:
  TapGestureRecognizer#bd989
════════════════════════════════════════════════════════════════════════════════════════════════════
Another exception was thrown: RangeError: Value not in range: -1

the error probably originated from somewere in this part of my code

// Task class to represent each task
class Task {
  final String id;
  final String text;
  bool isCompleted;
  final GlobalKey key;

  Task({required this.id, required this.text, this.isCompleted = false})
      : key = GlobalKey();
}

class HomePage extends StatefulWidget {
  final String title;

  const HomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  int _taskIdCounter = 0;
  List<Task> taskList = [];
  final textController = TextEditingController();
  final FocusNode textFieldFocus = FocusNode();
  int finishedTaskIndex = -1;
  final ApiService _apiService = ApiService(); // Use your singleton instance

  // Key for the list
  final GlobalKey _listKey = GlobalKey();

  // Map to keep track of task positions
  Map<Task, double> _taskPositions = {};
  double _itemHeight = 72.0; // Adjust based on your item height

  // Variables for animation
  Task? _movingTask;
  AnimationController? _tiltController;

  // Variables for storing deleted tasks for undo
  Task? _recentlyDeletedTask;
  int? _recentlyDeletedTaskIndex;

  // Function to obtain tasks from the server
  Future _getTasks() async {
    try {
      Map? data = await _apiService.getTasks();
      if (data == null || data.isEmpty) {
        // Failed to get data
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Não foi possível obter a lista de tarefas')),
        );
        await _apiService.updateTasks([], {});
      } else {
        setState(() {
          taskList = [];
          _taskIdCounter = 0;
          finishedTaskIndex = data["finishedTaskIndex"];

          List<String> list = List<String>.from(data["list"]);
          Map<String, bool> status = Map<String, bool>.from(data["status"]);
          for (var text in list) {
            _taskIdCounter++;
            taskList.add(Task(
              id: _taskIdCounter.toString(),
              text: text,
              isCompleted: status[text] ?? false,
            ));
          }
          _updateTaskPositions();
        });
      }
    } catch (e) {
      // Handle exception
    }
  }

  @override
  void initState() {
    super.initState();
    _getTasks(); // Fetch tasks when the widget is initialized
  }

  void _updateTaskPositions() {
    double position = 0.0;
    for (int i = 0; i < taskList.length; i++) {
      Task task = taskList[i];
      _taskPositions[task] = position;
      position += _itemHeight;
    }
  }

  // Function to add a task
  void _addTask(String st) {
    final trimmedTask = st.trim();
    if (trimmedTask.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Por favor, escreva uma tarefa antes de adicionar!')),
      );
      FocusScope.of(context).requestFocus(textFieldFocus);
    } else if (taskList.any((task) => task.text == trimmedTask)) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Essa tarefa já foi adicionada!')),
      );
      FocusScope.of(context).requestFocus(textFieldFocus);
    } else {
      setState(() {
        _taskIdCounter++;
        int insertIndex = finishedTaskIndex + 1;
        Task newTask = Task(id: _taskIdCounter.toString(), text: trimmedTask);
        taskList.insert(insertIndex, newTask);
        finishedTaskIndex++;
        _updateTaskPositions();
        textController.clear();
        _apiService.updateTasks(
          taskList.map((t) => t.text).toList(),
          {for (var t in taskList) t.text: t.isCompleted},
        );
      });
      FocusScope.of(context).requestFocus(textFieldFocus);
    }
  }

  // Function to delete a task with undo option via Snackbar
  void _deleteTask(Task task) {
    int index = taskList.indexOf(task);
    if (index == -1) return;

    setState(() {
      if (!task.isCompleted) {
        finishedTaskIndex--;
      }
      _recentlyDeletedTask = task;
      _recentlyDeletedTaskIndex = index;
      taskList.removeAt(index);
      _updateTaskPositions();
      _apiService.updateTasks(
        taskList.map((t) => t.text).toList(),
        {for (var t in taskList) t.text: t.isCompleted},
      );
    });

    // Show a Snackbar with Undo option
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('Tarefa "${task.text}" excluída'),
        duration: const Duration(seconds: 3),
        action: SnackBarAction(
          label: 'Desfazer',
          textColor: Colors.white,
          onPressed: () {
            // Undo deletion
            setState(() {
              taskList.insert(_recentlyDeletedTaskIndex!, _recentlyDeletedTask!);
              if (!_recentlyDeletedTask!.isCompleted) {
                finishedTaskIndex++;
              }
              _updateTaskPositions();
              _apiService.updateTasks(
                taskList.map((t) => t.text).toList(),
                {for (var t in taskList) t.text: t.isCompleted},
              );
            });
          },
        ),
      ),
    );
  }

  // Function to change the status (checked/unchecked) of a task
  void _changeTaskStatus(Task task, bool value) {
    setState(() {
      _movingTask = task;
      _tiltController?.dispose();
      _tiltController = AnimationController(
        duration: const Duration(milliseconds: 500),
        vsync: this,
      )..forward().whenComplete(() {
          setState(() {
            _movingTask = null;
            _tiltController?.dispose();
            _tiltController = null;
          });
        });

      // Reorder the taskList
      taskList.remove(task);
      if (value) {
        // Mark as completed
        task.isCompleted = value;
        taskList.insert(finishedTaskIndex, task);
        finishedTaskIndex--;
      } else {
        // Mark as uncompleted
        task.isCompleted = value;
        finishedTaskIndex++;
        taskList.insert(finishedTaskIndex, task);
      }
      _updateTaskPositions();
      _apiService.updateTasks(
        taskList.map((t) => t.text).toList(),
        {for (var t in taskList) t.text: t.isCompleted},
      );
    });
  }

  @override
  void dispose() {
    textController.dispose();
    textFieldFocus.dispose(); // Dispose the FocusNode
    _tiltController?.dispose();
    super.dispose();
  }

  Widget _buildTaskCard(Task task) {
    int index = taskList.indexOf(task);
    return Dismissible(
      key: Key(task.id),
      background: Container(
        color: Colors.green[400],
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.only(left: 20),
        child: const Icon(Icons.check, color: Colors.white),
      ),
      secondaryBackground: Container(
        color: Colors.red[400],
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 20),
        child: const Icon(Icons.delete, color: Colors.white),
      ),
      confirmDismiss: (direction) async {
        if (direction == DismissDirection.startToEnd) {
          // Left to right swipe (complete task)
          _changeTaskStatus(task, true);
          return false; // Prevents Dismissible from removing the widget
        } else if (direction == DismissDirection.endToStart) {
          // Right to left swipe (delete task)
          return true; // Allow Dismissible to remove the widget
        }
        return false;
      },
      onDismissed: (direction) {
        if (direction == DismissDirection.endToStart) {
          // Right to left swipe (delete task)
          _deleteTask(task);
        }
      },
      child: Card(
        margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0), // Adjust margins to reduce spacing
        color: (index % 2 == 0)
            ? Colors.indigo[300]
            : Colors.indigo[400],
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(9.0),
        ),
        child: CheckboxListTile(
          contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 0.0), // Adjust padding to reduce spacing
          controlAffinity: ListTileControlAffinity.leading,
          title: task.isCompleted
              ? Text(task.text,
                  style: const TextStyle(
                      decoration: TextDecoration.lineThrough,
                      color: Colors.white,
                      decorationColor: Colors.white,
                      decorationThickness: 1.5))
              : Text(task.text, style: const TextStyle(color: Colors.white)),
          value: task.isCompleted,
          checkColor: Colors.black,
          activeColor: Colors.white,
          onChanged: (bool? value) {
            if (value != null) {
              _changeTaskStatus(task, value);
            }
          },
          secondary: IconButton(
            icon: const Icon(Icons.delete_rounded, color: Colors.white),
            onPressed: () {
              _deleteTask(task);
            },
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        foregroundColor: Colors.white,
        backgroundColor: Colors.indigo[400],
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          // Input field and add button
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: textController,
                    autofocus: true,
                    focusNode: textFieldFocus,
                    onSubmitted: _addTask,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(30.0),
                      ),
                      filled: true,
                      hintStyle: TextStyle(color: Colors.grey[500]),
                      hintText: "Escreva sua tarefa",
                      fillColor: Colors.white70,
                    ),
                  ),
                ),
                const SizedBox(width: 10),
                IconButton(
                  icon: const Icon(Icons.add),
                  onPressed: () => _addTask(textController.text),
                  tooltip: 'Adicionar tarefa',
                ),
              ],
            ),
          ),
          // Task list
          Expanded(
            child: Stack(
              key: _listKey,
              children: [
                // Other tasks
                ...taskList.where((t) => t != _movingTask).map((task) {
                  double top = _taskPositions[task] ?? 0;
                  return AnimatedPositioned(
                    key: task.key,
                    duration: const Duration(milliseconds: 500),
                    curve: Curves.easeInOut,
                    left: 0,
                    right: 0,
                    top: top,
                    height: _itemHeight,
                    child: _buildTaskCard(task),
                  );
                }).toList(),
                // Moving task on top
                if (_movingTask != null)
                  AnimatedPositioned(
                    key: _movingTask!.key,
                    duration: const Duration(milliseconds: 500),
                    curve: Curves.easeInOut,
                    left: 0,
                    right: 0,
                    top: _taskPositions[_movingTask!] ?? 0,
                    height: _itemHeight,
                    child: AnimatedBuilder(
                      animation: _tiltController!,
                      builder: (context, child) {
                        double tilt = (1 - _tiltController!.value) * 0.1; // Tilt effect
                        return Transform.rotate(
                          angle: tilt,
                          child: _buildTaskCard(_movingTask!),
                        );
                      },
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}