Improve error handling in message view

This commit is contained in:
Nutcake 2023-05-16 15:57:44 +02:00
parent 57cbd4370b
commit 5d5b01b8a9
5 changed files with 232 additions and 202 deletions

View file

@ -124,10 +124,13 @@ class ApiClient {
if (response.statusCode == 403) { if (response.statusCode == 403) {
tryCachedLogin(); tryCachedLogin();
// TODO: Show the login screen again if cached login was unsuccessful. // TODO: Show the login screen again if cached login was unsuccessful.
throw "You are not authorized to do that."; throw "You are not authorized to do that";
}
if (response.statusCode == 500) {
throw "Internal server error";
} }
if (response.statusCode != 200) { if (response.statusCode != 200) {
throw "Unknown Error${kDebugMode ? ": ${response.statusCode}|${response.body}" : ""}"; throw "Unknown Error: ${response.statusCode}${kDebugMode ? "|${response.body}" : ""}";
} }
} }

View file

@ -196,6 +196,10 @@ class MessagingClient extends ChangeNotifier {
MessageCache _createUserMessageCache(String userId) => MessageCache(apiClient: _apiClient, userId: userId); MessageCache _createUserMessageCache(String userId) => MessageCache(apiClient: _apiClient, userId: userId);
void deleteUserMessageCache(String userId) {
_messageCache.remove(userId);
}
Future<void> loadUserMessageCache(String userId) async { Future<void> loadUserMessageCache(String userId) async {
final cache = getUserMessageCache(userId) ?? _createUserMessageCache(userId); final cache = getUserMessageCache(userId) ?? _createUserMessageCache(userId);
await cache.loadMessages(); await cache.loadMessages();

View file

@ -114,7 +114,7 @@ class MessageCache {
final List<Message> _messages = []; final List<Message> _messages = [];
final ApiClient _apiClient; final ApiClient _apiClient;
final String _userId; final String _userId;
Future? currentOperation; Object? error;
List<Message> get messages => _messages; List<Message> get messages => _messages;
@ -155,9 +155,14 @@ class MessageCache {
} }
Future<void> loadMessages() async { Future<void> loadMessages() async {
final messages = await MessageApi.getUserMessages(_apiClient, userId: _userId); error = null;
_messages.addAll(messages); try {
_ensureIntegrity(); final messages = await MessageApi.getUserMessages(_apiClient, userId: _userId);
_messages.addAll(messages);
_ensureIntegrity();
} catch (e) {
error = e;
}
} }
void _ensureIntegrity() { void _ensureIntegrity() {

View file

@ -2,6 +2,7 @@ import 'package:contacts_plus_plus/client_holder.dart';
import 'package:contacts_plus_plus/clients/messaging_client.dart'; import 'package:contacts_plus_plus/clients/messaging_client.dart';
import 'package:contacts_plus_plus/models/friend.dart'; import 'package:contacts_plus_plus/models/friend.dart';
import 'package:contacts_plus_plus/models/message.dart'; import 'package:contacts_plus_plus/models/message.dart';
import 'package:contacts_plus_plus/widgets/default_error_widget.dart';
import 'package:contacts_plus_plus/widgets/friends/friend_online_status_indicator.dart'; import 'package:contacts_plus_plus/widgets/friends/friend_online_status_indicator.dart';
import 'package:contacts_plus_plus/widgets/messages/messages_session_header.dart'; import 'package:contacts_plus_plus/widgets/messages/messages_session_header.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -78,213 +79,230 @@ class _MessagesListState extends State<MessagesList> with SingleTickerProviderSt
.of(context) .of(context)
.colorScheme .colorScheme
.surfaceVariant; .surfaceVariant;
return Scaffold( return Consumer<MessagingClient>(
appBar: AppBar( builder: (context, mClient, _) {
title: Row( final cache = mClient.getUserMessageCache(widget.friend.id);
crossAxisAlignment: CrossAxisAlignment.center, return Scaffold(
children: [ appBar: AppBar(
FriendOnlineStatusIndicator(userStatus: widget.friend.userStatus), title: Row(
const SizedBox(width: 8,), crossAxisAlignment: CrossAxisAlignment.center,
Text(widget.friend.username),
if (widget.friend.isHeadless) Padding(
padding: const EdgeInsets.only(left: 12),
child: Icon(Icons.dns, size: 18, color: Theme
.of(context)
.colorScheme
.onSecondaryContainer
.withAlpha(150),),
),
],
),
scrolledUnderElevation: 0.0,
backgroundColor: appBarColor,
),
body: Column(
children: [
if (sessions.isNotEmpty) Container(
constraints: const BoxConstraints(maxHeight: 64),
decoration: BoxDecoration(
color: appBarColor,
border: const Border(top: BorderSide(width: 1, color: Colors.black26),)
),
child: Stack(
children: [ children: [
ListView.builder( FriendOnlineStatusIndicator(userStatus: widget.friend.userStatus),
controller: _sessionListScrollController, const SizedBox(width: 8,),
scrollDirection: Axis.horizontal, Text(widget.friend.username),
itemCount: sessions.length, if (widget.friend.isHeadless) Padding(
itemBuilder: (context, index) => SessionTile(session: sessions[index]), padding: const EdgeInsets.only(left: 12),
child: Icon(Icons.dns, size: 18, color: Theme
.of(context)
.colorScheme
.onSecondaryContainer
.withAlpha(150),),
), ),
AnimatedOpacity( ],
opacity: _shevronOpacity, ),
curve: Curves.easeOut, scrolledUnderElevation: 0.0,
duration: const Duration(milliseconds: 200), backgroundColor: appBarColor,
child: Align( ),
alignment: Alignment.centerRight, body: Column(
child: Container( children: [
padding: const EdgeInsets.only(left: 16, right: 4, top: 1, bottom: 1), if (sessions.isNotEmpty) Container(
decoration: BoxDecoration( constraints: const BoxConstraints(maxHeight: 64),
gradient: LinearGradient( decoration: BoxDecoration(
begin: Alignment.centerLeft, color: appBarColor,
end: Alignment.centerRight, border: const Border(top: BorderSide(width: 1, color: Colors.black26),)
colors: [ ),
appBarColor.withOpacity(0), child: Stack(
appBarColor, children: [
appBarColor, ListView.builder(
], controller: _sessionListScrollController,
scrollDirection: Axis.horizontal,
itemCount: sessions.length,
itemBuilder: (context, index) => SessionTile(session: sessions[index]),
),
AnimatedOpacity(
opacity: _shevronOpacity,
curve: Curves.easeOut,
duration: const Duration(milliseconds: 200),
child: Align(
alignment: Alignment.centerRight,
child: Container(
padding: const EdgeInsets.only(left: 16, right: 4, top: 1, bottom: 1),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
appBarColor.withOpacity(0),
appBarColor,
appBarColor,
],
),
),
height: double.infinity,
child: const Icon(Icons.chevron_right),
), ),
), ),
height: double.infinity, )
child: const Icon(Icons.chevron_right), ],
), ),
), ),
) Expanded(
], child: Builder(
), builder: (context) {
), if (cache == null) {
Expanded( return const Column(
child: Consumer<MessagingClient>( mainAxisAlignment: MainAxisAlignment.start,
builder: (context, mClient, _) { children: [
final cache = mClient.getUserMessageCache(widget.friend.id); LinearProgressIndicator()
if (cache == null) { ],
return const Column( );
mainAxisAlignment: MainAxisAlignment.start, }
children: [ if (cache.error != null) {
LinearProgressIndicator() return DefaultErrorWidget(
], message: cache.error.toString(),
); onRetry: () {
} setState(() {
if (cache.messages.isEmpty) { mClient.deleteUserMessageCache(widget.friend.id);
return Center( });
child: Column( mClient.loadUserMessageCache(widget.friend.id);
mainAxisAlignment: MainAxisAlignment.center, },
children: [
const Icon(Icons.message_outlined),
Padding(
padding: const EdgeInsets.symmetric(vertical: 24),
child: Text(
"There are no messages here\nWhy not say hello?",
textAlign: TextAlign.center,
style: Theme
.of(context)
.textTheme
.titleMedium,
),
)
],
),
);
}
return ListView.builder(
controller: _messageScrollController,
reverse: true,
itemCount: cache.messages.length,
itemBuilder: (context, index) {
final entry = cache.messages[index];
if (index == cache.messages.length - 1) {
return Padding(
padding: const EdgeInsets.only(top: 12),
child: MessageBubble(message: entry,),
); );
} }
return MessageBubble(message: entry,); if (cache.messages.isEmpty) {
}, return Center(
); child: Column(
}, mainAxisAlignment: MainAxisAlignment.center,
), children: [
), const Icon(Icons.message_outlined),
AnimatedContainer( Padding(
decoration: BoxDecoration( padding: const EdgeInsets.symmetric(vertical: 24),
boxShadow: [ child: Text(
BoxShadow( "There are no messages here\nWhy not say hello?",
blurRadius: _showBottomBarShadow ? 8 : 0, textAlign: TextAlign.center,
color: Theme.of(context).shadowColor, style: Theme
offset: const Offset(0, 4), .of(context)
), .textTheme
], .titleMedium,
color: Theme.of(context).colorScheme.background, ),
), )
padding: const EdgeInsets.symmetric(horizontal: 4), ],
duration: const Duration(milliseconds: 250), ),
child: Row( );
children: [ }
Expanded( return ListView.builder(
child: Padding( controller: _messageScrollController,
padding: const EdgeInsets.all(8), reverse: true,
child: TextField( itemCount: cache.messages.length,
autocorrect: true, itemBuilder: (context, index) {
controller: _messageTextController, final entry = cache.messages[index];
maxLines: 4, if (index == cache.messages.length - 1) {
minLines: 1, return Padding(
onChanged: (text) { padding: const EdgeInsets.only(top: 12),
if (text.isNotEmpty && !_isSendable) { child: MessageBubble(message: entry,),
setState(() { );
_isSendable = true;
});
} else if (text.isEmpty && _isSendable) {
setState(() {
_isSendable = false;
});
} }
return MessageBubble(message: entry,);
}, },
decoration: InputDecoration( );
isDense: true, },
hintText: "Send a message to ${widget.friend ),
.username}...", ),
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), AnimatedContainer(
border: OutlineInputBorder( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24) boxShadow: [
) BoxShadow(
blurRadius: _showBottomBarShadow ? 8 : 0,
color: Theme.of(context).shadowColor,
offset: const Offset(0, 4),
),
],
color: Theme.of(context).colorScheme.background,
),
padding: const EdgeInsets.symmetric(horizontal: 4),
duration: const Duration(milliseconds: 250),
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8),
child: TextField(
enabled: cache != null && cache.error == null,
autocorrect: true,
controller: _messageTextController,
maxLines: 4,
minLines: 1,
onChanged: (text) {
if (text.isNotEmpty && !_isSendable) {
setState(() {
_isSendable = true;
});
} else if (text.isEmpty && _isSendable) {
setState(() {
_isSendable = false;
});
}
},
decoration: InputDecoration(
isDense: true,
hintText: "Message ${widget.friend
.username}...",
hintMaxLines: 1,
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24)
)
),
),
), ),
), ),
), Padding(
), padding: const EdgeInsets.only(left: 8, right: 4.0),
Padding( child: Consumer<MessagingClient>(
padding: const EdgeInsets.only(left: 8, right: 4.0), builder: (context, mClient, _) {
child: Consumer<MessagingClient>( return IconButton(
builder: (context, mClient, _) { splashRadius: 24,
return IconButton( onPressed: _isSendable ? () async {
splashRadius: 24, setState(() {
onPressed: _isSendable ? () async { _isSendable = false;
setState(() { });
_isSendable = false; final message = Message(
}); id: Message.generateId(),
final message = Message( recipientId: widget.friend.id,
id: Message.generateId(), senderId: apiClient.userId,
recipientId: widget.friend.id, type: MessageType.text,
senderId: apiClient.userId, content: _messageTextController.text,
type: MessageType.text, sendTime: DateTime.now().toUtc(),
content: _messageTextController.text, );
sendTime: DateTime.now().toUtc(), try {
mClient.sendMessage(message);
_messageTextController.clear();
setState(() {});
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Failed to send message\n$e",
maxLines: null,
),
),
);
setState(() {
_isSendable = true;
});
}
} : null,
iconSize: 28,
icon: const Icon(Icons.send),
); );
try { },
mClient.sendMessage(message); ),
_messageTextController.clear(); )
setState(() {}); ],
} catch (e) { ),
ScaffoldMessenger.of(context).showSnackBar( ),
SnackBar( ],
content: Text("Failed to send message\n$e",
maxLines: null,
),
),
);
setState(() {
_isSendable = true;
});
}
} : null,
iconSize: 28,
icon: const Icon(Icons.send),
);
},
),
)
],
),
), ),
], );
), }
); );
} }
} }

View file

@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts # In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix. # of the product and file versions while build-number is used as the build suffix.
version: 1.2.1+1 version: 1.2.2+1
environment: environment:
sdk: '>=3.0.0' sdk: '>=3.0.0'