Flutter implements a custom queue of tasks, first in, first out (FIFO), which executes one task before iterating over the next.

Usage Scenarios:

  • Queue Time-consuming task execution

Directly on the code:

typedef TaskCallback = void Function(bool success, dynamic result); Class TaskQueueUtils {bool _isTaskRunning = false; class TaskQueueUtils {bool _isTaskRunning = false; List<TaskItem> _taskList = []; bool get isTaskRunning => _isTaskRunning; Future addTask(Future future) { Completer completer = Completer(); TaskItem taskItem = TaskItem( content: future, callback: (success, result) { if (success) { completer.complete(result); } else { completer.completeError(result); }}); _taskList.add(taskItem); _doTask(); return completer.future; } void _doTask() async { if (_isTaskRunning) return; if (_taskList.isEmpty) return; TaskItem task = _taskList[0]; _isTaskRunning = true; var result; // Execute task try {result = await task.content; Task. callback(true, result); } catch (e) { task.callback(false, e); } finally { _taskList.removeAt(0); _isTaskRunning = false; } // recursive task _doTask(); } // TaskItem {final Future content; final TaskCallback callback; TaskItem({this.content, this.callback}); }Copy the code

Usage:

main() {
  TaskQueueUtils().addTask(Future.delayed(Duration(seconds: 2), () {
    print("task 1");
  }));
  TaskQueueUtils().addTask(Future.delayed(Duration(seconds: 1), () {
    print("task 2");
  }));
}
Copy the code

Task1 and task2 are simulated time-consuming tasks.