A complete screen
The whole thing in one widget — the agent's settings, a streaming answer, and a lifecycle that cleans up after itself.
Harbor & Pine’s help screen: the agent’s name and opening line from the dashboard, starter questions as chips, a streaming answer, four honest error sentences, and nothing left running when the person leaves.
The lifecycle
The screen
lib/chat_screen.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:tigerbase/tigerbase.dart';
/// One client for the app, not one per screen: each instance holds its own
/// HTTP client and its own cached config.
final tigerbase = Tigerbase(key: 'tb_your_key_here');
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key, required this.visitorId});
/// Stable across launches. A fresh id each time is a fresh person each
/// time, and the agent will not remember yesterday.
final String visitorId;
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
late final Conversation _chat;
late final Future<AgentConfig> _agent;
final _input = TextEditingController();
final _messages = <Message>[];
StreamSubscription<StreamEvent>? _turn;
String _streaming = '';
String? _failure;
@override
void initState() {
super.initState();
// Started once, in initState — not in build, which runs again on every
// rebuild and would fire a request per frame.
_agent = tigerbase.config();
_chat = tigerbase.conversation(visitorId: widget.visitorId);
}
@override
void dispose() {
// A screen that is gone should not still be receiving an answer.
_turn?.cancel();
_input.dispose();
super.dispose();
}
void _send(String question) {
final trimmed = question.trim();
if (trimmed.isEmpty || _turn != null) return;
setState(() {
_messages.add(Message(role: 'user', content: trimmed));
_streaming = '';
_failure = null;
_input.clear();
});
final buffer = StringBuffer();
_turn = _chat.ask(trimmed).listen(
(event) {
final chunk = event.chunk;
if (chunk == null) return;
buffer.write(chunk);
// mounted, because a chunk can arrive in the gap between the user
// leaving the screen and the subscription being cancelled.
if (mounted) setState(() => _streaming = buffer.toString());
},
onError: (Object error) {
if (!mounted) return;
setState(() {
_failure = _sentenceFor(error);
_streaming = '';
_turn = null;
});
},
onDone: () {
if (!mounted) return;
setState(() {
if (buffer.isNotEmpty) {
_messages.add(Message(role: 'model', content: buffer.toString()));
}
_streaming = '';
_turn = null;
});
},
cancelOnError: true,
);
}
/// Four situations, four sentences. One "something went wrong" leaves
/// somebody retrying a limit that will not move until next month.
String _sentenceFor(Object error) {
// Not a TigerbaseError: the connection dropped after the answer started.
if (error is! TigerbaseError) return 'The connection dropped. Try again?';
return switch (error.code) {
TigerbaseErrorCode.rateLimited =>
'A lot of people are asking at once. Try again in '
'${error.retryAfter?.inSeconds ?? 5} seconds.',
TigerbaseErrorCode.tooManyConversations => 'Busy right now. Try again shortly.',
TigerbaseErrorCode.network => 'You seem to be offline.',
// The detail reaches the account owner another way. A stranger using
// the app should not be reading it.
_ => 'The assistant is not available right now.',
};
}
@override
Widget build(BuildContext context) {
return FutureBuilder<AgentConfig>(
future: _agent,
builder: (context, snapshot) {
final agent = snapshot.data;
if (agent == null && snapshot.hasError) {
return const Center(child: Text('The assistant is unavailable.'));
}
if (agent == null) {
return const Center(child: CircularProgressIndicator());
}
// The agent's own language decides the direction, so an Arabic
// agent mirrors the layout without a second setting.
return Directionality(
textDirection:
agent.language == 'ar' ? TextDirection.rtl : TextDirection.ltr,
child: Scaffold(
appBar: AppBar(title: Text(agent.botName ?? 'Assistant')),
body: Column(
children: [
Expanded(child: _thread(agent)),
if (_failure != null)
Padding(
padding: const EdgeInsets.all(12),
child: Text(
_failure!,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
),
_composer(),
],
),
),
);
},
);
}
Widget _thread(AgentConfig agent) {
// The opening message and the starter questions are the first-open
// state: an empty thread tells somebody nothing about what to ask.
if (_messages.isEmpty && _streaming.isEmpty) {
return ListView(
padding: const EdgeInsets.all(16),
children: [
Text(
agent.initialMessage ?? 'Welcome to Harbor & Pine. How can we help?',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 16),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final question in agent.starterQuestions)
ActionChip(
label: Text(question),
onPressed: () => _send(question),
),
],
),
],
);
}
final rows = [
..._messages,
if (_streaming.isNotEmpty) Message(role: 'model', content: _streaming),
];
return ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: rows.length,
itemBuilder: (context, i) {
final message = rows[i];
final mine = message.role == 'user';
return Align(
alignment: mine ? Alignment.centerRight : Alignment.centerLeft,
child: Card(
child: Padding(
padding: const EdgeInsets.all(12),
child: Text(message.content),
),
),
);
},
);
}
Widget _composer() {
final busy = _turn != null;
return SafeArea(
child: Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: [
Expanded(
child: TextField(
controller: _input,
enabled: !busy,
onSubmitted: _send,
decoration: const InputDecoration(hintText: 'Ask anything'),
),
),
IconButton(
icon: const Icon(Icons.send),
onPressed: busy ? null : () => _send(_input.text),
),
],
),
),
);
}
}The four things that are easy to get wrong
| Fetching config in build() | build runs again on every rebuild, so that is a request per frame. Start it in initState and hand the future to a FutureBuilder. |
|---|---|
| Not cancelling the subscription | A screen that is gone should not still be receiving an answer. Cancel it in dispose. |
| setState after dispose | A chunk can arrive in the gap between the user leaving and the cancel landing. Check mounted. |
| One error message for everything | Two of the failures clear on their own and two never will. One sentence for all four leaves somebody retrying a monthly limit. |
WarningBefore you ship it
A native build sends no
Origin header, and the hosted API refuses requests without one. Test a release build against production — see Setup.TipThis is deliberately not a state-management opinion
Conversation is a plain object that holds a list and exposes a Stream. Put it behind Riverpod, Bloc, a ChangeNotifier or nothing at all — the package has no view on it, and a client that forced one would be wrong for most apps.