Home Flutter How to Keep an AI Task Running While Users Navigate Between Flutter...

How to Keep an AI Task Running While Users Navigate Between Flutter Screens

13
0

Use shared Flutter state for navigation, a backend job for durable execution, and a job ID to reconnect when the user returns.

A user starts an AI report and switches to another tab. When they return, the app should show the same report at its current stage. If they lock their phone or reopen the app later, they should still be able to find the result. Starting the request again wastes model calls and can produce a second report the user never asked for.

The architecture depends on how long the task needs to survive. An app-scoped controller can keep an in-memory task alive across Flutter routes. A backend-owned job lets the work continue when the app is suspended, the network drops, or the phone process ends. In both cases, screens observe the task rather than owning its execution. Flutter’s architecture guide places shared application data and refresh logic in repositories, where multiple views can access them.

Where Should AI Task State Live in Flutter?

What needs to survive?Where the task should liveHow the screen reconnects
Navigation between tabs or routes while the app is runningAn app- or session-scoped controller or repositoryRead the shared state by task ID
Backgrounding, network loss, or process terminationA backend worker with durable job stateFetch the current status by job ID
Progress across phones or other devicesAn authenticated backend job recordQuery the account’s active and recent jobs

A route pushed on top of another can leave the previous route mounted. Popping, replacing, or otherwise removing a route can dispose its widget state. That difference makes a navigation test with Navigator.push() alone misleading. A controller provided above the relevant Navigator or tab shell can outlive both screens, as long as its own scope stays mounted. Keep route disposal responsible for cleaning up screen subscriptions. Give cancelling the task its own explicit action.

Mobile background execution has its own rules. Android provides WorkManager for persistent work, and Apple provides APIs for eligible tasks that need to continue after backgrounding. For an AI report generated in the cloud, keeping execution on the backend avoids depending on how long the mobile OS lets the client run.

How Do You Build a Flutter Task That Survives Navigation?

  1. Start the task once. When the user taps Generate report, send POST /ai-jobs with an idempotency key for that submission. The backend should return the same job ID if it receives the same request again after a timeout. Start the job from the user action, rather than from a screen build or a status subscription.
  2. Persist status and results on the server. Store the job owner, current status, last update, and result reference. Start with queued, running, succeeded, failed, and cancelled. If the backend cannot measure real progress, show stages such as Reading documents or Writing report instead of a guessed percentage.
  3. Expose current state as well as updates. A returning screen needs the latest snapshot even if it missed every live event. Support a status endpoint alongside polling, server-sent events, or a Firestore listener. For streamed updates, use a revision or cursor so a reconnect can recover missed updates and a late event cannot overwrite newer state. Firestore’s Flutter API provides snapshots() for observing document changes.
  4. Reconcile when the app resumes. Use AppLifecycleListener.onResume to reload active jobs. On cold launch, query active and recent jobs for the signed-in account or restore locally cached job IDs and revalidate them. This also recovers a job submitted successfully just before the app closed.

What Does the Flutter Screen Own?

This widget observes an existing job. Its repository contract is to emit the latest known snapshot and then updates. It never starts inference.

class JobStatusView extends StatefulWidget {
  const JobStatusView({
    super.key,
    required this.jobId,
    required this.repository,
  });

  final String jobId;
  final AiJobRepository repository;

  @override
  State<JobStatusView> createState() => _JobStatusViewState();
}

class _JobStatusViewState extends State<JobStatusView> {
  late Stream<AiJob> _updates;

  @override
  void initState() {
    super.initState();
    _updates = widget.repository.watch(widget.jobId);
  }

  @override
  void didUpdateWidget(covariant JobStatusView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.jobId != widget.jobId ||
        oldWidget.repository != widget.repository) {
      _updates = widget.repository.watch(widget.jobId);
    }
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<AiJob>(
      key: ValueKey(_updates),
      stream: _updates,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return const Text('Could not refresh job status.');
        }
        final job = snapshot.data;
        return Text(job?.statusLabel ?? 'Loading job status…');
      },
    );
  }
}

Flutter’s StreamBuilder documentation recommends obtaining the stream before build. Creating it inside build can restart the asynchronous subscription on a parent rebuild. The stream key also resets the rendered snapshot when the widget switches to another job. In a production screen, keep “Could not refresh status” distinct from “The AI job failed.” A disconnected phone may be unable to see a job that’s still running normally.

How Five Companies Put These Patterns Into Practice

  • GeekyAnts documents a Flutter AI assistant built with BLoC for client state, SharedPreferences and Hive for local storage, and Firebase for the backend. It’s a documented example of separating Flutter state, local persistence, and backend services. The case study describes the stack and voice-query workflow, while the job-reconnect design above is an implementation pattern for this article.
  • Google documents how Flutter apps can use Cloud Firestore snapshot listeners to observe changing records. A backend worker can update a job document while different screens observe the same status.
  • OpenAI supports background responses that can be retrieved by response ID. Its documentation describes polling or using a completion webhook, giving an application backend a way to track inference independently of a Flutter screen.
  • AWS offers asynchronous invocation for supported Amazon Bedrock models. StartAsyncInvoke returns an invocation ARN, and GetAsyncInvoke retrieves its status. A backend can map that ARN to its own application job ID.
  • Temporal uses durable workflow execution to recover progress after failures. That approach fits a multi-step report that reads files, generates sections, and exports a result, where restarting the entire pipeline would repeat completed work.

What Should Teams Test Before Release?

Start a job, replace its route, and open it from another tab. Then repeat with airplane mode, a process kill, and a cold launch after the job finishes. The acceptance test is concrete: one submission produces one job ID, the same result is recoverable, and the app can distinguish a lost connection from a failed task. Also test cancellation while a result is being saved so the app shows whichever outcome the backend actually committed

Previous articleHow to Display and Correct Live Speech Transcripts in Flutter

LEAVE A REPLY

Please enter your comment!
Please enter your name here