Files
sure/mobile/lib/screens/chat_list_screen.dart
Tristan Katana 6a6548de64 feat(mobile): Add animated TypingIndicator for AI chat responses (#1269)
* feat(mobile): Add animated TypingIndicator widget for AI chat responses

Replaces the static CircularProgressIndicator + "AI is thinking..." text
with an animated TypingIndicator showing pulsing dots while the AI generates
a response. Respects the app color scheme so it works in light and dark themes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix: Normalize stagger progress to [0,1) in TypingIndicator to prevent negative opacity

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(mobile): fix typing indicator visibility and run pub get

The typing indicator was only visible for the duration of the HTTP
POST (~instant) because it was tied to `isSendingMessage`. It now
tracks the full AI response lifecycle via a new `isWaitingForResponse`
state that stays true through polling until the response stabilises.

- Add `isWaitingForResponse` to ChatProvider; set on poll start,
  clear on poll stop with notifyListeners so the UI reacts correctly
- Move TypingIndicator inside the ListView as an assistant bubble
  so it scrolls naturally with the conversation
- Add provider listener that auto-scrolls on every update while
  waiting for a response
- Redesign TypingIndicator: 3-dot sequential bounce animation
  (classic chat style) replacing the simultaneous fade

* feat(mobile): overhaul new-chat flow and fix typing indicator bugs
 chat is created lazily
  on first send, eliminating all pre-conversation flashes and crashes
- Inject user message locally into _currentChat immediately on createChat
  so it renders before the first poll completes
- Hide thinking indicator the moment the first assistant content arrives
  (was waiting one extra 2s poll cycle before disappearing)
- Fix double-spinner on new chat: remove manual showDialog spinner and
  use a local _isCreating flag on the FAB instead

* fix(mboile) : address PR review — widget lifecycle safety and new-chat regression

* Fic(mobile): Add mounted check in post-frame callback

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 22:57:46 +01:00

267 lines
9.2 KiB
Dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../providers/chat_provider.dart';
import 'chat_conversation_screen.dart';
class ChatListScreen extends StatefulWidget {
const ChatListScreen({super.key});
@override
State<ChatListScreen> createState() => _ChatListScreenState();
}
class _ChatListScreenState extends State<ChatListScreen> {
@override
void initState() {
super.initState();
_loadChats();
}
Future<void> _loadChats() async {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
final accessToken = await authProvider.getValidAccessToken();
if (accessToken == null) {
await authProvider.logout();
return;
}
await chatProvider.fetchChats(accessToken: accessToken);
}
Future<void> _handleRefresh() async {
await _loadChats();
}
Future<void> _openNewChat() async {
if (!mounted) return;
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ChatConversationScreen(chatId: null),
),
);
if (mounted) _loadChats();
}
String _formatDateTime(DateTime dateTime) {
final now = DateTime.now();
final difference = now.difference(dateTime);
if (difference.inMinutes < 1) {
return 'Just now';
} else if (difference.inHours < 1) {
return '${difference.inMinutes}m ago';
} else if (difference.inDays < 1) {
return '${difference.inHours}h ago';
} else if (difference.inDays < 7) {
return '${difference.inDays}d ago';
} else {
return '${dateTime.day}/${dateTime.month}/${dateTime.year}';
}
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Scaffold(
appBar: AppBar(
title: const Text('Chats'),
centerTitle: false,
actions: [
Padding(
padding: const EdgeInsets.only(top: 12, right: 12),
child: InkWell(
onTap: _handleRefresh,
child: const SizedBox(
width: 36,
height: 36,
child: Icon(Icons.refresh),
),
),
),
],
),
body: Consumer<ChatProvider>(
builder: (context, chatProvider, _) {
if (chatProvider.isLoading && chatProvider.chats.isEmpty) {
return const Center(
child: CircularProgressIndicator(),
);
}
if (chatProvider.errorMessage != null && chatProvider.chats.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error_outline,
size: 64,
color: colorScheme.error,
),
const SizedBox(height: 16),
Text(
'Failed to load chats',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
chatProvider.errorMessage!,
style: TextStyle(color: colorScheme.onSurfaceVariant),
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
ElevatedButton.icon(
onPressed: _handleRefresh,
icon: const Icon(Icons.refresh),
label: const Text('Try Again'),
),
],
),
),
);
}
if (chatProvider.chats.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.chat_bubble_outline,
size: 64,
color: colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
'No chats yet',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
'Start a new conversation with the AI assistant.',
style: TextStyle(color: colorScheme.onSurfaceVariant),
textAlign: TextAlign.center,
),
],
),
),
);
}
return RefreshIndicator(
onRefresh: _handleRefresh,
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: chatProvider.chats.length,
itemBuilder: (context, index) {
final chat = chatProvider.chats[index];
return Dismissible(
key: Key(chat.id),
direction: DismissDirection.endToStart,
background: Container(
color: Colors.red,
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: 16),
child: const Icon(
Icons.delete,
color: Colors.white,
),
),
confirmDismiss: (direction) async {
return await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Delete Chat'),
content: Text('Are you sure you want to delete "${chat.title}"?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Delete', style: TextStyle(color: Colors.red)),
),
],
),
);
},
onDismissed: (direction) async {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final accessToken = await authProvider.getValidAccessToken();
if (accessToken != null) {
await chatProvider.deleteChat(
accessToken: accessToken,
chatId: chat.id,
);
}
},
child: ListTile(
leading: CircleAvatar(
backgroundColor: colorScheme.primaryContainer,
child: Icon(
Icons.chat,
color: colorScheme.onPrimaryContainer,
),
),
title: Text(
chat.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: chat.lastMessageAt != null
? Text(_formatDateTime(chat.lastMessageAt!))
: null,
trailing: chat.messageCount != null
? Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: colorScheme.secondaryContainer,
borderRadius: BorderRadius.circular(12),
),
child: Text(
'${chat.messageCount}',
style: TextStyle(
color: colorScheme.onSecondaryContainer,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
)
: null,
onTap: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChatConversationScreen(chatId: chat.id),
),
);
_loadChats();
},
),
);
},
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _openNewChat,
tooltip: 'New Chat',
child: const Icon(Icons.add),
),
);
}
}