Every Flutter AI-chat demo I've seen starts with the same pubspec.yaml:
dependencies:
provider: ^6.1.2
flutter_markdown: ^0.7.0
# + dio, freezed, json_annotation, ...
That is a perfectly reasonable place to start — and a terrible place to stay if you want the UI layer of a product you can hand to a client. Six months later flutter pub get resolves against a package that stopped shipping, and the "starter" costs a day of upgrades before it starts.
So when I built the UI for an AI chat product (onboarding → auth → streaming chat → subscription paywall → settings), I set one hard constraint: no third-party packages at all. Only flutter_localizations + intl, which are pinned by the SDK anyway.
This post is about what that constraint actually cost, and the four places where the interesting problems were: state, streaming text, auto-scroll, and the free-quota-to-paywall funnel. All code below is from the working project.

1. The whole app state in one ChangeNotifier
The app has three things that outlive a screen: theme mode, language, and the "is this user Pro" entitlement. That's it. One class:
class AppState extends ChangeNotifier {
AppState({
ThemeMode themeMode = ThemeMode.system,
AppLanguage language = AppLanguage.zh,
bool isPro = false,
}) : _themeMode = themeMode,
_language = language,
_isPro = isPro;
ThemeMode _themeMode;
AppLanguage _language;
bool _isPro;
ThemeMode get themeMode => _themeMode;
AppLanguage get language => _language;
bool get isPro => _isPro;
Locale get locale => _language.locale;
AppStrings get strings => AppStrings(_language);
void setThemeMode(ThemeMode mode) {
if (_themeMode == mode) return;
_themeMode = mode;
notifyListeners();
}
void setLanguage(AppLanguage language) {
if (_language == language) return;
_language = language;
notifyListeners();
}
void setPro(bool value) {
if (_isPro == value) return;
_isPro = value;
notifyListeners();
}
}
The early return when the value hasn't changed is not micro-optimisation — it is what stops a notifyListeners() from rebuilding the entire app when the user taps the theme that is already selected.
Exposing it: InheritedNotifier, not InheritedWidget
InheritedNotifier is the part people forget exists. It is an InheritedWidget that subscribes to a Listenable for you, so you don't write addListener / removeListener / didUpdateWidget by hand:
class AppScope extends InheritedNotifier<AppState> {
const AppScope({super.key, required AppState state, required super.child})
: super(notifier: state);
static AppState of(BuildContext context) {
final AppScope? scope =
context.dependOnInheritedWidgetOfExactType<AppScope>();
assert(scope != null, 'AppScope is missing above this widget.');
return scope!.notifier!;
}
}
extension AppContextX on BuildContext {
AppState get app => AppScope.of(this);
AppStrings get strings => AppStrings(AppScope.of(this).language);
}
Wired at the root:
AnimatedBuilder(
animation: _state,
builder: (context, _) => AppScope(
state: _state,
child: MaterialApp(
theme: AppTheme.light(),
darkTheme: AppTheme.dark(),
themeMode: _state.themeMode,
locale: _state.locale,
home: const OnboardingScreen(),
),
),
)
And every screen reads context.app.isPro or context.strings.title exactly like it would read context.watch<AppState>().
What you give up: selector granularity. provider's Selector / context.select<T> lets one widget subscribe to one field. Here, AppScope.of(context) subscribes the caller to all of AppState, so flipping the language rebuilds any widget that reads the theme. For three fields with a few rebuilds per user tap, that is invisible. If you need finer control, the answer isn't a package — it's more notifiers: a ThemeController, a SessionState, each with its own InheritedNotifier. The pattern scales by splitting, not by adding dependencies.
What you gain: no resolution drift, no API churn when the ecosystem moves, and a state layer a junior dev can read top to bottom in five minutes. Which matters when the thing you're selling is a starting point.
2. Streaming text: substring is a bug waiting for an emoji
A fake streaming reply is a timer that appends a few characters at a time. The naive version:
reply.text = full.substring(0, cursor); // don't do this
String.substring indexes UTF-16 code units. Cut a 3-unit chunk in the middle of a surrogate pair — an emoji, or anything outside the BMP — and you get a lone high surrogate.
Flutter renders it as a replacement glyph, and if you later do length-based maths on the string you're now off by one for the rest of the reply. A Chinese or Japanese reply streams fine (CJK sits in the BMP), which is exactly why this bug ships: it only shows up when the demo text contains an emoji, or when a user pastes one into their prompt and the "reply" echoes it.
The fix, with no packages:
final List<String> runes = full.runes
.map((int rune) => String.fromCharCode(rune))
.toList(growable: false);
int cursor = 0;
_timer = Timer.periodic(const Duration(milliseconds: 22), (timer) {
cursor += 3;
if (cursor >= runes.length) {
timer.cancel();
setState(() {
reply
..text = full // snap to the exact string
..code = const CodeSnippet(language: 'dart', code: _sampleCode)
..isStreaming = false;
_isReplying = false;
});
return;
}
setState(() => reply.text = runes.sublist(0, cursor).join());
});
Three details worth stealing:
-
.runes→String.fromCharCode→sublistkeeps every chunk on a code-point boundary. If you also need grapheme clusters (flags, skin tones, family emoji), that genuinely requires thecharacterspackage —runescovers the 95% case and stays dependency-free. I chose the 95%. -
Snap to
fullat the end instead of letting the loop finish onsublist. Otherwise the final frame can be a rune short of the real text, and atext == expectedassertion in a widget test flakes. -
The code block arrives after the text finishes. Streaming a code string into a syntax-highlighted widget looks broken — the highlighter re-parses an incomplete string on every frame. So the reply streams as plain text, then the message gains its
CodeSnippetand the bubble re-renders as a copyable card, once.
3. Auto-scroll: the bug that looks like bad performance
A chat feed must follow the newest token. The obvious implementation:
_scroll.animateTo(_scroll.position.maxScrollExtent,
duration: const Duration(milliseconds: 220), curve: Curves.easeOut);
This is the single worst thing you can do to a streaming feed. A 45 fps stream restarts that 220 ms animation ~45 times a second, so the scroll never completes, never reaches the bottom, and the text visibly lags behind. Users read it as jank in the rendering, but it's the animation controller fighting itself.
What works instead: jump, don't animate, after the frame lays out.
void _scrollToBottom({bool force = false}) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_scroll.hasClients) return;
final position = _scroll.position;
final bottom = position.maxScrollExtent;
if ((bottom - position.pixels).abs() < 1) return;
if (!force && (!_pinnedToBottom || _feedDragging)) return;
position.jumpTo(bottom);
});
}
The _pinnedToBottom / _feedDragging guard is the other half. Someone who scrolled up to re-read an earlier answer must not be yanked to the bottom because a new token arrived. So the feed tracks whether the reader is still within a small slack of the bottom, and only then follows; the user's own message passes force: true.
The one nobody tests: viewport resize
Open the keyboard mid-stream and maxScrollExtent grows while the viewport shrinks. If you only scroll on new content, the last bubble ends up half-hidden behind the keyboard. WidgetsBindingObserver has the hook:
@override
void didChangeMetrics() {
if (!_pinnedToBottom || _feedDragging) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_scroll.hasClients || _feedDragging) return;
final bottom = _scroll.position.maxScrollExtent;
if ((_scroll.position.pixels - bottom).abs() > 0.5) {
_scroll.jumpTo(bottom);
}
});
}
Same rule, second trigger: content growth and viewport change both re-pin, and both respect a reader who has scrolled away.
4. The free-quota → paywall funnel
The business model of an AI app is a meter. Five free messages, then the paywall. In code that's four lines in _send, and their order is the whole design:
void _send([String? preset]) {
if (_isReplying) return;
final text = (preset ?? _input.text).trim();
if (text.isEmpty) return;
_dismissKeyboard();
final pro = context.app.isPro;
if (!pro && _freeLeft <= 0) {
_openPaywall(); // quota already spent → wall, before spending
return;
}
setState(() {
_messages.add(ChatMessage(id: _nextId(), role: ChatRole.user, text: text));
_messages.add(ChatMessage(id: _nextId(), role: ChatRole.assistant, isStreaming: true));
if (!pro) _freeLeft -= 1;
_isReplying = true;
});
_input.clear();
_scrollToBottom(force: true);
_streamReply(text);
}
Points that are easy to get wrong:
- Check before decrementing. If you decrement first and check after, the user's 6th message is swallowed with no reply and no paywall — the worst of both.
-
The meter lives in the chat screen, the entitlement lives in
AppState. Quota is session UI state (it resets per app launch in the template); entitlement is app-wide and belongs with theme and language. Mixing them makes "restore purchases" impossible to reason about. -
The paywall returns a
bool.Navigator.push<bool>→upgraded == true→_openPaywallshows a "Pro unlocked" snackbar. One flag, one source of truth, and everyPRObadge in the app lights up because they all read the same notifier. -
The meter is always visible, not only when empty: a small
4 leftchip in the chat header. A counter that only appears at zero reads as a bait-and-switch; a counter that counts down is a product.
5. The three UI details that cost more time than the architecture
Status bar icons on a light theme
Light theme, Scaffold with no AppBar (onboarding, auth): the clock renders white on white and the screen looks broken. Two pieces fix it:
static SystemUiOverlayStyle systemOverlayStyle(Brightness brightness) {
if (brightness == Brightness.dark) {
return SystemUiOverlayStyle.light.copyWith(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.light,
statusBarBrightness: Brightness.dark, // iOS, inverted by design
systemNavigationBarIconBrightness: Brightness.light,
);
}
return SystemUiOverlayStyle.dark.copyWith(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark,
statusBarBrightness: Brightness.light,
systemNavigationBarIconBrightness: Brightness.dark,
);
}
AppBarTheme.systemOverlayStyle handles screens that have an app bar. For the ones that don't, wrap the app in an AnnotatedRegion from MaterialApp.builder:
builder: (context, child) => AnnotatedRegion<SystemUiOverlayStyle>(
key: appStatusBarKey,
value: AppTheme.systemOverlayStyle(Theme.of(context).brightness),
child: child ?? const SizedBox.shrink(),
),
Note statusBarBrightness is the iOS one and means the opposite of statusBarIconBrightness (iOS wants the background brightness). Getting it backwards gives you correct Android and invisible iOS, which is a fun way to spend an afternoon. A key on the region also gives widget tests a handle to assert the overlay style in both themes.
Dismissing the keyboard on purpose
TextField dismisses on tap-outside by default, which is not enough for a chat screen: tapping Send, opening the model-picker sheet, or pushing a screen all leave a focused field behind. One line, called deliberately before each of those gestures:
void _dismissKeyboard() => FocusManager.instance.primaryFocus?.unfocus();
Plus keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag on the feed, so dragging the conversation closes it too. The subtle part: _dismissKeyboard() runs before you push a sheet. A showModalBottomSheet over an open keyboard both hides the sheet's content and leaves the field focused behind it.
Not overflowing at 320 dp with 1.3× text
Everything in the kit was run at 320 / 360 / 430 dp and at 1.3× text scale, because that is where "it looks great on my simulator" dies. The fixes are unglamorous — Flexible + TextOverflow.ellipsis on the header row, SingleChildScrollView inside dialogs, and capping sheet height against the actual screen instead of the default 9/16:
final media = MediaQuery.of(context);
final double maxHeight = media.size.height * 0.85 - media.padding.top * 0.5;
6. What the 31 widget tests actually catch
Widget tests are cheap here precisely because there are no packages giving you test-doubles — pumpWidget with AppScope above the screen is the whole setup:
- smoke flow: onboarding → sign in → chat → paywall → "Pro unlocked" badge appears
- streaming render and the code card that arrives when it finishes
- runtime zh ↔ en switch without a restart
- auth tab and onboarding indicator transitions
- no overflow at 320 / 360 / 430 dp, 1.3× text, wide screens
- status-bar icon brightness in light and dark
- keyboard dismissal on send, blank tap, list drag and sheet open
flutter analyze → No issues found. (Flutter 3.50 / Dart 3.14). flutter test → 31 tests, all passed. Zero pubspec packages beyond the SDK's own.
That is the argument I'd make for the constraint: a dependency-free UI layer is not just fewer upgrades — it's a smaller surface for tests to mock, and a state model small enough that "what happens when quota hits zero" is answerable by reading one file.
Where this came from
This is the reference app I packaged as Flutter AI Starter Kit — the five screens above (onboarding, auth, AI chat workspace, paywall, settings), light/dark, zh/en, streaming replies, free-quota funnel, commercial licence.
- Showcase + screenshots: https://github.com/StephenColor/flutter-ai-starter-kit
- Full source, early-bird $2.90: https://stephencolor.gumroad.com/l/flutter-ai-starter-kit
The tech specs, honestly: Flutter 3.22+, Material 3 with a single seed colour, ChangeNotifier + InheritedNotifier, an in-house zh/en string table, 15 Dart files, 31 passing widget tests, flutter analyze clean, 0 third-party dependencies. Auth, payment and the AI endpoint are demo implementations with documented swap points — RevenueCat / Firebase Auth / your model provider drop in where the timers are.
If you're building something similar and only take one thing from this post: stop using substring to stream text. Everything else in the feed follows from that.
Top comments (0)