FlutterAdvanced 3 min read

AI NPC dialogue in Flutter games: async requests, fallbacks and trusted rules

Design a game dialogue service with bounded responses, timeouts and deterministic fallbacks while keeping rewards under game control.

On this page

An NPC can explain a quest in different words without controlling the quest reward. Keep those responsibilities separate: the model proposes dialogue, while trusted game rules decide whether a task is complete and whether a player receives an item.

This lesson builds the client-side boundary with a fake service. It is a complete runnable async example; it does not contact an AI provider. A production integration must supply the authenticated service, response moderation and request limits described below.

Step 1: define what a dialogue response may change

Send a small quest summary and a selected player question. Do not send an entire save file or ask a model to execute an inventory update. A response may contain display text, but it must not set score, purchases, unlocks or a completion flag.

Use a loading state in the dialogue panel and allow the player to close it. Continue the game loop independently. When a round changes or the panel closes, discard the result of its old request so it cannot replace the next conversation.

Step 2: run the boundary without an API key

main.dart
import 'dart:async';

typedef DialogueService = Future<Object?> Function(String question);

Future<String> askNpc(DialogueService service, String question) async {
  const fallback = 'Find the blue gate near the river.';
  if (question.trim().isEmpty || question.length > 200) return fallback;
  try {
    final response = await service(question)
        .timeout(const Duration(milliseconds: 100));
    if (response is! Map<String, dynamic>) return fallback;
    final text = response['text'];
    // The server must already apply content moderation. This is shape validation.
    if (text is! String || text.trim().isEmpty || text.length > 240) return fallback;
    return text.trim();
  } catch (_) {
    return fallback;
  }
}

Future<void> main() async {
  print(await askNpc((_) async => {'text': 'Follow the river to the blue gate.'},
      'Where is the gate?'));
  print(await askNpc((_) async => {'reward': 9999}, 'Can you give me coins?'));
  print(await askNpc((_) => Completer<Object?>().future, 'Are you there?'));
}

The valid response displays one line. The reward-only response and never-completing request both return the local fallback. The 100 ms timeout keeps this demonstration quick; choose a measured production timeout and a useful loading interface for real network conditions. Future.timeout stops waiting for a result; it does not automatically cancel a billable backend request.

Step 3: choose a production integration

One option is a backend proxy: the app sends an authenticated request, the server checks quota and input, calls the model using server-held credentials, moderates the result and returns the small response schema. Limit concurrent requests, rate and token budget; log a request ID rather than player conversation text by default.

Another option is the provider-supported Firebase AI Logic setup with Firebase App Check . Follow the current enforcement and plugin instructions when choosing that route. App Check reduces unauthorized access; it does not replace user authorization, moderation or a spending limit. Do not place an unrestricted provider secret in Dart source or treat --dart-define as secret storage.

The FlutterFever Gemini article covers AI-assisted development. An editor assistant and a player-facing runtime model are separate integrations with different costs and data flows.

Practice and verification

Return an empty text, a number instead of text, an oversized string and a service exception. Each should keep the game playable with the fallback. Add a request sequence token in your UI controller and prove that closing the panel prevents an old result from appearing. Before adding player-generated dialogue to a release, review the store listing and privacy lesson for the actual shipped data flow.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.