How to Track Token Usage Gemini Streaming in Flutter

Two tools, two moments: `countTokens` tells you the input cost before you send anything, and `usageMetadata` gives you the full input/output/thinking split after the response. On streams the metadata only lands on the last chunk โ€” here's the firebase_ai 5.0.0 pattern that captures it.

Call countTokens before the request for the input cost, then read usageMetadata after it for the full split. On streams, usageMetadata is null on every intermediate chunk and appears only on the last one โ€” capture it there. Gemini Live API models support neither. The firebase_ai 5.0.0 Dart pattern below does both in under 30 lines. ๐ŸŽฌ Watch: The "Calculate an example AI bill" chapter (02:31) plus Gemini pricing examples (02:58) โ€” input vs. output tokens, per-million pricing, and reasoning-token charges. Input vs. output tokens, per-million pricing, and reasoning tokens in ~6 minutes โ€” the cost model your Flutter usageMetadata guard is enforcing. Data unavailable โฑ Data unavailable ยท GenAI Geek โ€” click to play inline, or watch on YouTube . how to track token usage gemini streaming: minimal working example This is the complete pattern for Firebase AI Logic with firebase_ai 5.0.0 (Flutter BoM 5.0.0). It assumes you already have a streaming model wired up โ€” see the streaming guide if not. import &#x27;package:firebase_ai/firebase_ai.dart&#x27;; import &#x27;package:flutter/foundation.dart&#x27;; Future<void> streamWithMetering(String prompt) async { final model = FirebaseAI.googleAI() .generativeModel(model: &#x27;gemini-3.8-flash&#x27;); // 1. PRE-FLIGHT: input-only estimate before anything is sent. final pre = await model.countTokens([Content.text(prompt)]); debugPrint(&#x27;Pre-flight input tokens: ${pre.totalTokens}&#x27;); // 2. STREAM: usageMetadata is null on every intermediate chunk โ€” // it only arrives on the LAST chunk. Capture the last non-null one. UsageMetadata? usage; final buffer = StringBuffer(); final stream = model.generateContentStream([Content.text(prompt)]); await for (final chunk in stream) { final text = chunk.text; // render this as it arrives ifโ€ฆ

Explore