CodeBlanks Logo Icon CodeBlanks

callbackDispatcher

Define a background callback with callbackDispatcher.

What is callbackDispatcher?

callbackDispatcher is the top-level function called when a background task runs. It runs in a separate isolate, so it cannot access the app's main state. The task id arrives via the task parameter and the appropriate work is performed.

bool callbackDispatcher(String task) {
  if (task == 'sync') {
    // sync data
  }
  return true;
}

The task parameter

callbackDispatcher receives a task id that identifies which task is running. This id matches the name given when the task was scheduled. Inside the function you use if or switch to perform the appropriate work.

bool callbackDispatcher(String task) {
  switch (task) {
    case 'sync':
      break;
  }
  return true;
}

Practice Write a callbackDispatcher

Write a top-level callbackDispatcher function that takes String task, returns true for the 'sync' id, otherwise false. In main, call it with the 'sync' id and print the result.

Starter code

main.dart
// callbackDispatcher fonksiyonunu yaz
// String task parametresi alsın
// 'sync' kimliği için true döndürsün

void main() {
  // 'sync' kimliğiyle çağır, sonucu yazdır
}

Sample solution

main.dart
bool callbackDispatcher(String task) {
  if (task == 'sync') {
    return true;
  }
  return false;
}

void main() {
  print(callbackDispatcher('sync'));
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why must callbackDispatcher be a top-level function?

  • Because it cannot be defined inside main
  • Because only top-level functions can be async
  • Because it runs in a separate isolate and cannot access class state Correct answer
  • Because the compiler only compiles top-level functions

Explanation: Because callbackDispatcher runs in a separate isolate, it cannot access app state; therefore it must be top-level and independent.

2 Check the task id

Question
bool callbackDispatcher(String ____) {
  if (task == 'sync') {
    return true;
  }
  return false;
}
Answer
bool callbackDispatcher(String task) {
  if (task == 'sync') {
    return true;
  }
  return false;
}

Explanation: The callbackDispatcher function takes the parameter named task; this is the task identifier.

3 callbackDispatcher parts

Term Meaning
callbackDispatcher Background callback
task Task identifier
isolate Separate execution environment
top-level Top-level function

All lessons in Advanced