Как в Dart выполнить тяжелую операцию в фоне?

Как в Dart выполнить тяжелую операцию в фоне? Есть например код?

void main() {
  print('startApp');
  hardOperation();
  print('runApp');
}

hardOperation() {
  print("startHardOperation");
  List list = List(100000000);
  list.forEach((element) {});
  print("stopHardOperation");
}

Вывод:

I/flutter (29084): startApp 
I/flutter (29084): startHardOperation // Ждет пока переберет массив
I/flutter (29084): stopHardOperation
I/flutter (29084): runApp

Как выполнить например данную операцию, но при этом, что бы код после начала hardOperation() не ждал когда выполниться hardOperation и выполнялся дальше:

I/flutter (29084): startApp 
I/flutter (29084): startHardOperation
I/flutter (29084): runApp
I/flutter (29084): stopHardOperation

Пробовал по-всякому, использовал Future, async, await. Можно конечно использовать отдельный изолят, но мне нужен доступ к массиву главного изолята. Интересует именно как сделать в главном изоляте.


Ответы (1 шт):

Автор решения: Tiarait

Для выполнение тяжелых задач в Android обычно переходят в фоновый поток и там выполняют работу, чтобы не блокировать основной поток и избегать ошибок ANR.

Пример задачи которая выполняется асинхронно loadData()

Future<void> loadData() async {
  //здесь ваш код
}

Источник - flutter.dev

Flutter. Асинхронность и параллельность (Хабр)

UPD для вашего примера

void main() {
  print('startApp');
  Future(hardOperation).then((_) {
    print('Future is complete');
  });
  print('runApp');
}

Future<void> hardOperation() async {
  print("startHardOperation");
  List list = List(100000000);
  list.forEach((element) {});
  print("stopHardOperation");
}

Результат

I/flutter (18585): startApp
I/flutter (18585): runApp
I/flutter (18585): startHardOperation
I/flutter (18585): stopHardOperation
I/flutter (18585): Future is complete
→ Ссылка