Home Flutter How to Resume AI Tasks After a Flutter App Returns from the...

How to Resume AI Tasks After a Flutter App Returns from the Background

13
0

Recover AI jobs after app switching, a network drop, or process death using Flutter lifecycle events and a persistent backend task ID.

A user starts an AI document summary, switches apps to check an email, and comes back a minute later. The original connection may be gone. The summary may already be complete. If the Flutter app submits the prompt again as soon as it resumes, it can generate a second summary while the first one is still running.

The reliable pattern is to resume observing the original task. Start the AI work on the backend, save its task ID, and fetch its current state when Flutter returns to the foreground. The same recovery path can restore a completed result after the operating system has terminated the app.

Why the Flutter lifecycle callback is only the starting point

Flutter exposes application state through AppLifecycleListener and AppLifecycleState. A transition to resumed is a good time to reconcile the screen with the backend. Flutter also warns that apps can skip lifecycle notifications, especially when they are terminated unexpectedly. On iOS, an app can be suspended after entering the background. On Android, the system can kill a cached process to reclaim resources. Save recovery information while the app is running, as soon as the task is accepted.

For a cloud-backed AI job, keep three pieces of state separate:

StateWhere it livesWhat happens when the app returns
Task identityLocal storage, backed by an account-scoped server recordFlutter locates the original task.
Execution status and resultBackend database or workflow serviceFlutter fetches the current state or completed output.
Connection stateFlutter memoryThe app opens a new status request or reconnects to a supported stream.

A connection can disappear while the underlying job keeps running. Treating a dropped connection as a failed generation is what causes many duplicate submissions.

Design a task API that can recover from a lost response

A document summarizer might use POST /ai/tasks to start work and GET /ai/tasks/{id} to check its status. The creation endpoint can return 202 Accepted with a task ID once it has durably accepted the job. The status endpoint can return queued, running, completed, failed, or cancelled. For a completed task, it returns the saved summary or a reference to the result.

There is a second failure window before Flutter receives the task ID. The backend can accept the request just as the device loses its connection. To recover, generate and persist a submission key before sending the request. If the response is lost, an authenticated lookup by that key can recover the task ID. Alternatively, a backend that explicitly supports idempotent creation can return the existing task when the client resends the same input and key. Enforce that mapping atomically on the server and scope it to the authenticated account.

On the device, a small account-scoped record can hold the submission key, task ID, and last known status. Flutter’s SQLite cookbook shows how to persist structured records using sqflite. Keep prompts, transcripts, and generated content out of that recovery record when the task ID is sufficient. On a cold start, load the saved IDs after authentication. A server endpoint listing recent tasks can also recover jobs when the local record is missing.

Refresh the original task when Flutter resumes

The following Dart example observes one existing task. It takes an authenticated Dio client with timeouts configured and a task ID loaded by the parent screen. It checks immediately if the app is already in the foreground, polls while the task is active, and cancels the status request when the app leaves resumed. The request identity check also keeps a late response from updating the screen after another lifecycle transition.

import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class AiTaskStatus extends StatefulWidget {
  const AiTaskStatus({
    super.key,
    required this.api,
    required this.taskId,
  });

  final Dio api;
  final String taskId;

  @override
  State<AiTaskStatus> createState() => _AiTaskStatusState();
}

class _AiTaskStatusState extends State<AiTaskStatus> {
  late final AppLifecycleListener _lifecycle;
  CancelToken? _request;
  Timer? _poll;
  String _message = 'Checking task status…';
  bool _canRetry = false;

  bool get _isForeground =>
      WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed;

  @override
  void initState() {
    super.initState();
    _lifecycle = AppLifecycleListener(onStateChange: (state) {
      if (state == AppLifecycleState.resumed) {
        unawaited(_refresh());
      } else {
        _stopObserving();
      }
    });

    if (_isForeground) unawaited(_refresh());
  }

  Future<void> _refresh() async {
    if (!mounted || !_isForeground || _request != null) return;

    _poll?.cancel();
    final request = CancelToken();
    _request = request;
    var pollAgain = false;

    try {
      final response = await widget.api.get<Map<String, dynamic>>(
        '/ai/tasks/${Uri.encodeComponent(widget.taskId)}',
        cancelToken: request,
      );

      if (!mounted || !identical(_request, request)) return;

      final data = response.data;
      final status = data?['status'];
      pollAgain = status == 'queued' || status == 'running';

      setState(() {
        _canRetry = false;
        _message = switch (status) {
          'queued' => 'Waiting to start…',
          'running' => 'Generating your summary…',
          'completed' => data?['result'] as String? ?? 'Summary ready.',
          'failed' => 'The task failed.',
          'cancelled' => 'The task was cancelled.',
          _ => 'Task status unavailable.',
        };
      });
    } on DioException catch (error) {
      if (!mounted || !identical(_request, request)) return;

      final code = error.response?.statusCode;
      setState(() {
        _canRetry = code == null || code == 408 || (code >= 500 && code < 600);
        _message = switch (code) {
          401 => 'Sign in again to recover this task.',
          403 || 404 || 410 => 'This task is no longer available.',
          429 => 'Too many status checks. Reopen the task later.',
          _ => 'Could not refresh task status.',
        };
      });
    } finally {
      if (identical(_request, request)) {
        _request = null;
        if (pollAgain && mounted && _isForeground) {
          _poll = Timer(const Duration(seconds: 3), () {
            unawaited(_refresh());
          });
        }
      }
    }
  }

  void _stopObserving() {
    _poll?.cancel();
    final request = _request;
    _request = null;
    request?.cancel();
  }

  @override
  void dispose() {
    _lifecycle.dispose();
    _stopObserving();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Column(
        children: [
          Text(_message),
          if (_canRetry)
            TextButton(
              onPressed: () => unawaited(_refresh()),
              child: const Text('Check again'),
            ),
        ],
      );
}

Use ValueKey(taskId) when building this widget so switching to a different task creates a fresh observer. The three-second interval and string result are example API choices. For a high-volume app, use a server-directed polling interval or reconnect backoff. Check again calls the status endpoint for the same task. A separate Cancel generation control would call a backend cancellation endpoint. Cancelling the Dio request only stops the phone’s current status check.

When is it worth resuming the stream?

If the user only needs the finished summary, recovering the job status and final result is usually enough. Replaying partial output becomes useful when the experience depends on seeing text or progress as it arrives.

For a resumable stream, give each event a sequence number. Keep the last applied sequence alongside the partial output, or reload a server snapshot before reconnecting. On resume, request only later events and ignore duplicates. If the replay window has expired, fetch the latest snapshot or final result. OpenAI’s Responses API documents a concrete example: a background response created with streaming enabled can reconnect using the last event’s sequence_number as starting_after.

How five companies approach AI task continuity

These examples show different parts of the same problem, from recording the state of a run to retrieving a result after the connection has gone away.

CompanyDocumented practice
GeekyAntsIts engineering write-up describes using run ledgers to track task progress, review outcomes, model behavior, and cost. The records also capture configuration and version details that help engineers investigate a run. The published example concerns traceability, which supports a recovery design, while the Flutter lifecycle implementation is the example in this article.
OpenAIThe Responses API supports background jobs that can be polled by response ID or tracked through completion webhooks. Eligible responses started in streaming mode can also resume from an event sequence.
Google CloudIts Veo examples show video generation as a long-running operation. The caller keeps the operation handle and checks it until the video is ready.
Amazon Web ServicesAWS Step Functions exposes DescribeExecution, which accepts an execution ARN and returns the workflow’s status. A backend can map that status to the simpler task states shown in a mobile UI.
VercelThe AI SDK’s useChat stream-resumption example uses persisted messages and a mapping from each chat to its active stream. It is a web SDK example that illustrates the server-side storage and reconnection contract a Flutter client can adopt.

Test the transitions that cause duplicate jobs

  • Background while the task is running. Return after it completes and verify that Flutter shows the saved result without calling the creation endpoint again.
  • Terminate the process after submission. Relaunch, restore the signed-in account, and recover the task through its saved ID or submission key.
  • Switch apps repeatedly. Verify that each foreground session has at most one active status request and that an old response cannot overwrite a newer state.
  • Return without connectivity. Preserve the task ID and show a status-check error. When the network returns, check the original task again.
  • Change accounts before reopening. Verify that neither cached task IDs nor server responses expose the previous account’s results.

The clearest acceptance test is to start a job, terminate the app before the response arrives, and sign back in. The same job should appear with its current status, and the backend should show that the AI work was submitted only once.

Previous articleBiometric Confirmation for Sensitive AI Actions in Flutter

LEAVE A REPLY

Please enter your comment!
Please enter your name here