improvements

main_production_copilot
Sikander Saleem 2 months ago
parent 2200c07b75
commit 8062ba8446

@ -18,6 +18,7 @@ class CopilotProvider extends ChangeNotifier {
String? sessionId; String? sessionId;
String? errorMessage; String? errorMessage;
StreamSubscription? _streamSub; StreamSubscription? _streamSub;
Future<void> loadHistory() async { Future<void> loadHistory() async {
historyLoading = true; historyLoading = true;
errorMessage = null; errorMessage = null;
@ -41,19 +42,18 @@ class CopilotProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
} }
Future<void> deleteHistory(String threadId) async { Future<void> deleteHistory(String threadId) async {
final prevList = List<CopilotHistoryItem>.from(history); final prevList = List<CopilotHistoryItem>.from(history);
history.removeWhere((h) => h.threadId == threadId);
notifyListeners();
try { try {
final res = await ApiManager.instance.delete( final res = await ApiManager.instance.delete(URLs.copilotDeleteQueryHistory(threadId), body: const {});
URLs.copilotDeleteQueryHistory(threadId),
body: const {}, // API ignores the body for this route-bound id endpoint
);
final decoded = jsonDecode(res.body); final decoded = jsonDecode(res.body);
final success = decoded is Map && decoded['isSuccess'] == true && decoded['data'] == true; final success = decoded is Map && decoded['isSuccess'] == true && decoded['data'] == true;
if (!success) { if (success) {
history.removeWhere((h) => h.threadId == threadId);
notifyListeners();
} else {
history = prevList; // rollback on failure history = prevList; // rollback on failure
errorMessage = (decoded is Map ? decoded['message'] : null) ?? "Failed to delete"; errorMessage = (decoded is Map ? decoded['message'] : null) ?? "Failed to delete";
notifyListeners(); notifyListeners();
@ -90,6 +90,7 @@ class CopilotProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
} }
void startNewConversation() { void startNewConversation() {
_streamSub?.cancel(); _streamSub?.cancel();
sessionId = null; sessionId = null;
@ -124,6 +125,7 @@ class CopilotProvider extends ChangeNotifier {
_onStreamError(assistantMsg, e); _onStreamError(assistantMsg, e);
} }
} }
Future<void> sendAudio(File audioFile) async { Future<void> sendAudio(File audioFile) async {
if (isStreaming) return; if (isStreaming) return;
sessionId ??= _generateSessionId(); sessionId ??= _generateSessionId();
@ -218,8 +220,7 @@ class CopilotProvider extends ChangeNotifier {
return; return;
} }
notifyListeners(); notifyListeners();
} catch (_) { } catch (_) {}
}
} }
void _onStreamError(CopilotMessage assistantMsg, Object e) { void _onStreamError(CopilotMessage assistantMsg, Object e) {
@ -247,11 +248,3 @@ class CopilotProvider extends ChangeNotifier {
super.dispose(); super.dispose();
} }
} }

@ -44,6 +44,7 @@ class CopilotMessage {
DateTime? timestamp; DateTime? timestamp;
bool isStreaming; bool isStreaming;
bool isError; bool isError;
// Local path of a recorded audio file for a user's voice query (never a remote // Local path of a recorded audio file for a user's voice query (never a remote
// download URL - the backend never sends audio back). Used to let the user // download URL - the backend never sends audio back). Used to let the user
// replay their own sent voice message, same as Chat's audio playback. // replay their own sent voice message, same as Chat's audio playback.
@ -120,7 +121,7 @@ class CopilotStreamContent {
class CopilotHistoryItem { class CopilotHistoryItem {
final String threadId; final String threadId;
final String firstHumanMessage; final String firstHumanMessage;
final DateTime updatedAt; final String updatedAt;
CopilotHistoryItem({ CopilotHistoryItem({
required this.threadId, required this.threadId,
@ -131,7 +132,6 @@ class CopilotHistoryItem {
factory CopilotHistoryItem.fromJson(Map<String, dynamic> json) => CopilotHistoryItem( factory CopilotHistoryItem.fromJson(Map<String, dynamic> json) => CopilotHistoryItem(
threadId: json['threadId'] ?? '', threadId: json['threadId'] ?? '',
firstHumanMessage: json['firstHumanMessage'] ?? '', firstHumanMessage: json['firstHumanMessage'] ?? '',
updatedAt: DateTime.tryParse(json['updatedAt'] ?? '') ?? DateTime.now(), updatedAt: json['updatedAt'] ?? '',
); );
} }

@ -12,7 +12,9 @@ import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import '../controller/copilot_provider.dart'; import '../controller/copilot_provider.dart';
import '../widgets/copilot_message_bubble.dart'; import '../widgets/copilot_message_bubble.dart';
enum _InputState { idle, recording, recorded } enum _InputState { idle, recording, recorded }
class CopilotChatPage extends StatefulWidget { class CopilotChatPage extends StatefulWidget {
final bool isNewConversation; final bool isNewConversation;
@ -106,11 +108,17 @@ class _CopilotChatPageState extends State<CopilotChatPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: DefaultAppBar(title: "Copilot Assistant", actions: [ appBar: DefaultAppBar(
'history_icon'.toSvgAsset(width: 24, height: 24).onPress((){ title: "Copilot Assistant",
Navigator.push(context, MaterialPageRoute(builder: (_) => const CopilotHistoryPage())).then((_) => context.read<CopilotProvider>().loadHistory()); actions: [
}).paddingOnly(end: 12), IconButton(
],), onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const CopilotHistoryPage())),
style: const ButtonStyle(tapTargetSize: MaterialTapTargetSize.shrinkWrap),
icon: "history_icon".toSvgAsset(width: 24, height: 24, color: AppColor.icon2Color(context)),
constraints: const BoxConstraints(),
),
],
),
body: Column( body: Column(
children: [ children: [
Expanded( Expanded(
@ -326,7 +334,7 @@ class _ShimmerBubble extends StatelessWidget {
).toShimmer(context: context, isShow: true); ).toShimmer(context: context, isShow: true);
final name = Text( final name = Text(
isSender ? "Me" : "Copilot",//check the api if they send the user name isSender ? "Me" : "Copilot", //check the api if they send the user name
style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50, fontWeight: FontWeight.w600), style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50, fontWeight: FontWeight.w600),
).toShimmer(context: context, isShow: true); ).toShimmer(context: context, isShow: true);
@ -360,8 +368,3 @@ class _ShimmerBubble extends StatelessWidget {
); );
} }
} }

@ -3,8 +3,10 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/modules/copilot/model/copilot_message_model.dart'; import 'package:test_sa/modules/copilot/model/copilot_message_model.dart';
import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
@ -38,38 +40,37 @@ class _CopilotHistoryPageState extends State<CopilotHistoryPage> {
} }
void _openConversation(String threadId) { void _openConversation(String threadId) {
Navigator.push( // Navigator.push(
context, // context,
CupertinoPageRoute( // CupertinoPageRoute(
builder: (_) => const CopilotChatPage( // builder: (_) => const CopilotChatPage(
isNewConversation: false, // isNewConversation: false,
), // ),
), // ),
).then( // ).then(
(_) => context.read<CopilotProvider>().loadHistory(), // (_) => context.read<CopilotProvider>().loadHistory(),
); // );
context.read<CopilotProvider>().loadConversation(threadId); context.read<CopilotProvider>().loadConversation(threadId);
Navigator.pop(context);
} }
void _startNewConversation() { void _startNewConversation() {
context.read<CopilotProvider>().startNewConversation(); context.read<CopilotProvider>().startNewConversation();
Navigator.pop(context);
Navigator.push( // Navigator.push(
context, // context,
CupertinoPageRoute( // CupertinoPageRoute(
builder: (_) => const CopilotChatPage( // builder: (_) => const CopilotChatPage(
isNewConversation: true, // isNewConversation: true,
), // ),
), // ),
).then( // ).then(
(_) => context.read<CopilotProvider>().loadHistory(), // (_) => context.read<CopilotProvider>().loadHistory(),
); // );
} }
List<CopilotHistoryItem> _filteredHistory( List<CopilotHistoryItem> _filteredHistory(List<CopilotHistoryItem> history) {
List<CopilotHistoryItem> history,
) {
final query = _searchQuery.trim().toLowerCase(); final query = _searchQuery.trim().toLowerCase();
if (query.isEmpty) { if (query.isEmpty) {
@ -88,8 +89,10 @@ class _CopilotHistoryPageState extends State<CopilotHistoryPage> {
title: "Copilot History", title: "Copilot History",
actions: [ actions: [
IconButton( IconButton(
icon: const Icon(Icons.chat_bubble),
onPressed: _startNewConversation, onPressed: _startNewConversation,
style: const ButtonStyle(tapTargetSize: MaterialTapTargetSize.shrinkWrap),
icon: Icon(Icons.chat_bubble, color: AppColor.icon2Color(context)),
constraints: const BoxConstraints(),
), ),
], ],
), ),
@ -106,12 +109,6 @@ class _CopilotHistoryPageState extends State<CopilotHistoryPage> {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
const Icon(
Icons.chat_bubble_outline,
size: 56,
color: AppColor.neutral120,
),
16.height,
Text( Text(
"No conversations yet", "No conversations yet",
style: AppTextStyles.heading6.copyWith( style: AppTextStyles.heading6.copyWith(
@ -135,27 +132,20 @@ class _CopilotHistoryPageState extends State<CopilotHistoryPage> {
final filteredHistory = _filteredHistory(provider.history); final filteredHistory = _filteredHistory(provider.history);
return Column( return Column(
spacing: 8,
children: [ children: [
8.height,
_buildSearchBar(context), _buildSearchBar(context),
8.height,
if (filteredHistory.isEmpty) if (filteredHistory.isEmpty)
Expanded( Expanded(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
const Icon( Icon(Icons.search_off, color: AppColor.icon2Color(context), size: 20),
Icons.search_off,
size: 48,
color: AppColor.neutral120,
),
12.height, 12.height,
Text( Text(
"No conversations found", "No conversations found",
style: AppTextStyles.heading6.copyWith( style: AppTextStyles.heading6.copyWith(color: AppColor.lightTextColor(context)),
color: AppColor.neutral120,
),
), ),
], ],
).center, ).center,
@ -163,18 +153,13 @@ class _CopilotHistoryPageState extends State<CopilotHistoryPage> {
else else
Expanded( Expanded(
child: ListView.separated( child: ListView.separated(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.all(16),
horizontal: 16,
),
itemCount: filteredHistory.length, itemCount: filteredHistory.length,
separatorBuilder: (context, index) => 12.height, separatorBuilder: (context, index) => 12.height,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final item = filteredHistory[index]; final item = filteredHistory[index];
return messageHistoryCard( return messageHistoryCard(item: item, provider: provider);
item: item,
provider: provider,
);
}, },
), ),
), ),
@ -186,91 +171,56 @@ class _CopilotHistoryPageState extends State<CopilotHistoryPage> {
} }
Widget _buildSearchBar(BuildContext context) { Widget _buildSearchBar(BuildContext context) {
return AppTextFormField( return SearchBar(
labelText: "", // focusNode: searchFocusNode,
hintText: context.translation.search, elevation: WidgetStateProperty.all<double>(0),
showBorder: false, backgroundColor: WidgetStateProperty.all<Color?>(AppColor.background(context)),
showShadow: false, leading: Icon(Icons.search, color: AppColor.iconColor(context)),
// backgroundColor: AppColor.fieldBgColor(context), textStyle: WidgetStateProperty.all<TextStyle>(
prefixIcon: Icon( TextStyle(color: AppColor.textColor(context), fontSize: 16.0),
Icons.search,
color: context.isDark ? AppColor.neutral10 : AppColor.neutral20,
size: 19,
), ),
textInputType: TextInputType.text, hintStyle: WidgetStateProperty.all<TextStyle>(
contentPadding: EdgeInsets.zero, TextStyle(color: AppColor.textColor(context), fontSize: 14.0),
hintStyle: AppTextStyles.bodyText.copyWith(
color: context.isDark ? AppColor.neutral10 : AppColor.neutral20,
), ),
style: AppTextStyles.bodyText.copyWith( hintText: 'Search',
color: AppColor.textStyleColor(context), onChanged: (queryString) {
), _searchQuery = queryString;
onChange: (value) { setState(() {});
setState(() {
_searchQuery = value;
});
}, },
) ).paddingOnly(top: 16, start: 16, end: 16);
.toShadowContainer(
context,
showShadow: false,
)
.paddingOnly(start: 16, end: 16);
} }
Widget messageHistoryCard({ Widget messageHistoryCard({required CopilotHistoryItem item, required CopilotProvider provider}) {
required CopilotHistoryItem item,
required CopilotProvider provider,
}) {
return Row( return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
spacing: 12,
children: [ children: [
Row( Icon(
mainAxisAlignment: MainAxisAlignment.spaceBetween, Icons.chat_bubble,
color: AppColor.icon2Color(context),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
spacing: 4,
children: [ children: [
Icon( InfoHeaderWidget(item.firstHumanMessage),
Icons.chat_bubble, InfoTextLabelWidget(label: item.updatedAt.toServiceRequestDetailsFormat),
color: AppColor.icon2Color(context),
),
16.width,
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InfoHeaderWidget(
item.firstHumanMessage,
),
4.height,
InfoTextLabelWidget(
label: _formatDate(item.updatedAt),
),
],
),
], ],
).expanded,
IconButton(
onPressed: () async {
Utils.showLoading(context);
await provider.deleteHistory(item.threadId);
Utils.hideLoading(context);
},
style: const ButtonStyle(tapTargetSize: MaterialTapTargetSize.shrinkWrap),
icon: "delete_icon".toSvgAsset(width: 20, height: 20),
constraints: const BoxConstraints(),
), ),
"delete_icon"
.toSvgAsset(
height: 20,
width: 20,
)
.onPress(
() => provider.deleteHistory(item.threadId),
),
], ],
) ).toShadowContainer(context).onPress(() {
.toShadowContainer(
context,
showShadow: false,
)
.onPress(() {
_openConversation(item.threadId); _openConversation(item.threadId);
}); });
} }
String _formatDate(DateTime date) {
return "${date.day.toString().padLeft(2, '0')}/"
"${date.month.toString().padLeft(2, '0')}/"
"${date.year} "
"${date.hour.toString().padLeft(2, '0')}:"
"${date.minute.toString().padLeft(2, '0')}";
}
} }

@ -5,6 +5,7 @@ import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';
import 'package:test_sa/views/widgets/sound/sound_player.dart'; import 'package:test_sa/views/widgets/sound/sound_player.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
import '../model/copilot_message_model.dart'; import '../model/copilot_message_model.dart';
@ -33,12 +34,7 @@ class CopilotMessageBubble extends StatelessWidget {
final senderHeader = Row( final senderHeader = Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Text( const InfoTextLabelWidget(label: "Me"),
"Me",
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50, fontWeight: FontWeight.w600),
),
8.width, 8.width,
_avatar, _avatar,
], ],
@ -61,7 +57,8 @@ class CopilotMessageBubble extends StatelessWidget {
padding: const EdgeInsets.all(8), padding: const EdgeInsets.all(8),
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.75), constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.75),
decoration: BoxDecoration( decoration: BoxDecoration(
color: AppColor.white50, color: AppColor.assetGroupBackground(context),
border: Border.all(color: AppColor.borderColor(context)),
borderRadius: BorderRadius.circular(6), borderRadius: BorderRadius.circular(6),
), ),
child: Column( child: Column(
@ -98,12 +95,13 @@ class CopilotMessageBubble extends StatelessWidget {
children: [ children: [
_avatar, _avatar,
8.width, 8.width,
Text( const InfoTextLabelWidget(label: "Copilot"),
"Copilot", // Text(
overflow: TextOverflow.ellipsis, // "Copilot",
maxLines: 1, // overflow: TextOverflow.ellipsis,
style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50, fontWeight: FontWeight.w600), // maxLines: 1,
), // style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50, fontWeight: FontWeight.w600),
// ),
], ],
); );
return Align( return Align(
@ -119,6 +117,7 @@ class CopilotMessageBubble extends StatelessWidget {
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.75), constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.75),
decoration: BoxDecoration( decoration: BoxDecoration(
color: AppColor.background(context), color: AppColor.background(context),
border: Border.all(color: AppColor.borderColor(context)),
borderRadius: BorderRadius.circular(6), borderRadius: BorderRadius.circular(6),
), ),
child: Column( child: Column(

@ -30,18 +30,15 @@ class AppDrawer extends StatelessWidget {
final settingProvider = Provider.of<SettingProvider>(context, listen: false); final settingProvider = Provider.of<SettingProvider>(context, listen: false);
final userProvider = Provider.of<UserProvider>(context, listen: false); final userProvider = Provider.of<UserProvider>(context, listen: false);
return Drawer( return Drawer(
backgroundColor: AppColor.background(context), backgroundColor: AppColor.background(context),
width: MediaQuery width: MediaQuery.of(context).size.width * .8,
.of(context) child: SafeArea(
.size top: false,
.width * .8, child: Column(
child: SafeArea( mainAxisAlignment: MainAxisAlignment.start,
top: false, crossAxisAlignment: CrossAxisAlignment.start,
child: Column( children: [
mainAxisAlignment: MainAxisAlignment.start, Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
@ -55,8 +52,8 @@ class AppDrawer extends StatelessWidget {
child: snapshot.profileImage != null child: snapshot.profileImage != null
? Image.file(snapshot.profileImage!) ? Image.file(snapshot.profileImage!)
: (snapshot.user?.profilePhotoName?.isNotEmpty ?? false) : (snapshot.user?.profilePhotoName?.isNotEmpty ?? false)
? Image.network(snapshot.user!.profilePhotoName!) ? Image.network(snapshot.user!.profilePhotoName!)
: Icon(Icons.person, size: 50, color: AppColor.icon2Color(context)), : Icon(Icons.person, size: 50, color: AppColor.icon2Color(context)),
), ),
), ),
); );
@ -66,72 +63,72 @@ class AppDrawer extends StatelessWidget {
), ),
8.height, 8.height,
(userProvider.user?.username ?? "").heading4(context).custom(color: AppColor.labelTextStyleColor(context)), (userProvider.user?.username ?? "").heading4(context).custom(color: AppColor.labelTextStyleColor(context)),
if ((userProvider.user?.email ?? "").isNotEmpty)(userProvider.user!.email!).heading6(context).custom(color: AppColor.lightTextColor(context)), if ((userProvider.user?.email ?? "").isNotEmpty) (userProvider.user!.email!).heading6(context).custom(color: AppColor.lightTextColor(context)),
16.height, 16.height,
const Divider().defaultStyle(context), const Divider().defaultStyle(context),
ListView( ListView(
padding: const EdgeInsets.only(top: 24), padding: const EdgeInsets.only(top: 24),
children: [ children: [
// drawerItem("drawer_notification", context.translation.notifications, context).onPress(() => Navigator.of(context).pushNamed(NotificationsPage.id)), // drawerItem("drawer_notification", context.translation.notifications, context).onPress(() => Navigator.of(context).pushNamed(NotificationsPage.id)),
// 18.height, // 18.height,
// drawerItem("notification_setting", 'Notification Settings'.addTranslation, context).onPress(() => Navigator.of(context).pushNamed(NotificationSettingPage.id)), // drawerItem("notification_setting", 'Notification Settings'.addTranslation, context).onPress(() => Navigator.of(context).pushNamed(NotificationSettingPage.id)),
// 18.height, // 18.height,
// drawerItem("help_center", context.translation.helpCenter, context) /*.onPress(() => Navigator.of(context).pushNamed(HelpCenterPage.id))*/, // drawerItem("help_center", context.translation.helpCenter, context) /*.onPress(() => Navigator.of(context).pushNamed(HelpCenterPage.id))*/,
// 18.height, // 18.height,
// drawerItem("rate_us", context.translation.rateUs, context), // drawerItem("rate_us", context.translation.rateUs, context),
// 18.height, // 18.height,
drawerItem("setting", context.translation.settings, context).onPress(() => Navigator.of(context).pushNamed(SettingsPage.id)), drawerItem("setting", context.translation.settings, context).onPress(() => Navigator.of(context).pushNamed(SettingsPage.id)),
18.height, 18.height,
drawerItem("setting", "Copilot", context).onPress(() { drawerItem("setting", "Copilot", context).onPress(() {
context.read<CopilotProvider>().startNewConversation(); context.read<CopilotProvider>().startNewConversation();
Navigator.push(context, MaterialPageRoute(builder: (_) => const CopilotChatPage(isNewConversation: true))).then((_) => context.read<CopilotProvider>().loadHistory()); Navigator.push(context, MaterialPageRoute(builder: (_) => const CopilotChatPage(isNewConversation: true))).then((_) => context.read<CopilotProvider>().loadHistory());
}), }),
18.height, 18.height,
drawerItem("site_request_icon", "Site Request", context).onPress(() => Navigator.of(context).pushNamed(SiteRequestHistoryScreen.routeName)), drawerItem("site_request_icon", "Site Request", context).onPress(() => Navigator.of(context).pushNamed(SiteRequestHistoryScreen.routeName)),
18.height, 18.height,
if (userProvider.user != null && settingProvider.isUserFlowMedical == false && userProvider.user?.employeeIsHMG == false) if (userProvider.user != null && settingProvider.isUserFlowMedical == false && userProvider.user?.employeeIsHMG == false)
drawerItem("swipe", "Swipe History", context).onPress(() => Navigator.of(context).pushNamed(SwipeHistoryView.routeName)), drawerItem("swipe", "Swipe History", context).onPress(() => Navigator.of(context).pushNamed(SwipeHistoryView.routeName)),
// 18.height, // 18.height,
// drawerItem("report", context.translation.reportBg, context) /*.onPress(() => Navigator.of(context).pushNamed(ReportBugPage.id))*/, // drawerItem("report", context.translation.reportBg, context) /*.onPress(() => Navigator.of(context).pushNamed(ReportBugPage.id))*/,
// 18.height, // 18.height,
// drawerItem("whats_new", context.translation.whatsNew, context), // drawerItem("whats_new", context.translation.whatsNew, context),
], ],
).expanded, ).expanded,
drawerItem("logout", context.translation.logout, context, color: AppColor.red30).onPress(() async { drawerItem("logout", context.translation.logout, context, color: AppColor.red30).onPress(() async {
bool result = await showDialog( bool result = await showDialog(
context: context, context: context,
builder: (_) => AAlertDialog(title: context.translation.signOut, content: context.translation.logoutAlert), builder: (_) => AAlertDialog(title: context.translation.signOut, content: context.translation.logoutAlert),
); );
if (result) { if (result) {
bool isSuccess = await userProvider.logout(context); bool isSuccess = await userProvider.logout(context);
if (isSuccess) { if (isSuccess) {
settingProvider.resetSettings(); settingProvider.resetSettings();
userProvider.reset(); userProvider.reset();
Navigator.of(context).pop(); Navigator.of(context).pop();
Navigator.of(context).pop(); Navigator.of(context).pop();
Navigator.of(context).pushNamedAndRemoveUntil(LoginPage.routeName, (routes) => true); Navigator.of(context).pushNamedAndRemoveUntil(LoginPage.routeName, (routes) => true);
} }
} }
}), }),
16.height, 16.height,
const Divider().defaultStyle(context), const Divider().defaultStyle(context),
16.height, 16.height,
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Text( Text(
"Powered By Cloud Solutions", "Powered By Cloud Solutions",
style: AppTextStyles.heading3.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral50, fontSize: 12), style: AppTextStyles.heading3.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral50, fontSize: 12),
textScaleFactor: AppStyle.getScaleFactor(context), textScaleFactor: AppStyle.getScaleFactor(context),
), ),
6.width, 6.width,
Image.asset("assets/images/cloud_logo.png", width: 32, height: 32) Image.asset("assets/images/cloud_logo.png", width: 32, height: 32)
], ],
) )
], ],
).paddingOnly(top: 66, start: 16, end: 24, bottom: 18), ).paddingOnly(top: 66, start: 16, end: 24, bottom: 18),
), ),
); );
} }

@ -697,8 +697,8 @@ class _MyAssetsPageState extends State<MyAssetsPage> with SingleTickerProviderSt
if (predictedAssetList.isNotEmpty) { if (predictedAssetList.isNotEmpty) {
Navigator.push(context, MaterialPageRoute(builder: (context) => PredictDeviceView(predictedAsset: predictedAssetList))); Navigator.push(context, MaterialPageRoute(builder: (context) => PredictDeviceView(predictedAsset: predictedAssetList)));
} else { } else {
Fluttertoast.showToast(msg: 'No Predicted asset found', toastLength: Toast.LENGTH_LONG); context.showInfoDialog("No Predicted asset found");
debugPrint('No Predicted asset found in the response.'); // Fluttertoast.showToast(msg: 'No Predicted asset found', toastLength: Toast.LENGTH_LONG);
} }
} }
} catch (e) { } catch (e) {

@ -23,8 +23,6 @@ class PredictDeviceView extends StatefulWidget {
} }
class _PredictDeviceViewState extends State<PredictDeviceView> with SingleTickerProviderStateMixin { class _PredictDeviceViewState extends State<PredictDeviceView> with SingleTickerProviderStateMixin {
late AssetProvider _devicesProvider;
bool showListView = true;
late AnimationController _animationController; late AnimationController _animationController;
@override @override
@ -45,133 +43,56 @@ class _PredictDeviceViewState extends State<PredictDeviceView> with SingleTicker
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
_devicesProvider = Provider.of<AssetProvider>(context);
return Scaffold( return Scaffold(
resizeToAvoidBottomInset: false, appBar: const DefaultAppBar(title: 'Predicated Devices'),
appBar: DefaultAppBar( body: SafeArea(
title: 'Predicated Devices', child: ListView.separated(
actions: [ key: const ValueKey('list_view'),
IconButton( padding: const EdgeInsets.all(16),
icon: Icon(!showListView ? Icons.view_list_sharp : Icons.grid_view_outlined, color: AppColor.icon2Color(context)), itemCount: widget.predictedAsset.length,
padding: EdgeInsets.zero, separatorBuilder: (listContext, itemIndex) => 12.height,
iconSize: 20, itemBuilder: (listContext, itemIndex) {
visualDensity: VisualDensity.compact, // Calculate staggered animation delay
tooltip: !showListView ? "View as List" : "View as Grid", final delay = itemIndex * 0.08;
onPressed: () => setState(() { final animation = Tween<double>(begin: 0.0, end: 1.0).animate(
showListView = !showListView; CurvedAnimation(
}), parent: _animationController,
), curve: Interval(
], delay.clamp(0.0, 0.7),
), (delay + 0.4).clamp(0.0, 1.0),
body: Stack( curve: Curves.easeOut,
children: [ ),
AnimatedSwitcher( ),
duration: const Duration(milliseconds: 500), );
child: showListView
? ListView.separated(
key: const ValueKey('list_view'),
padding: const EdgeInsets.all(16),
itemCount: widget.predictedAsset.length,
separatorBuilder: (listContext, itemIndex) => 12.height,
itemBuilder: (listContext, itemIndex) {
// Calculate staggered animation delay
final delay = itemIndex * 0.08;
final animation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: _animationController,
curve: Interval(
delay.clamp(0.0, 0.7),
(delay + 0.4).clamp(0.0, 1.0),
curve: Curves.easeOut,
),
),
);
final slideAnimation = Tween<Offset>(
begin: const Offset(0.0, 0.15),
end: Offset.zero,
).animate(
CurvedAnimation(
parent: _animationController,
curve: Interval(
delay.clamp(0.0, 0.7),
(delay + 0.4).clamp(0.0, 1.0),
curve: Curves.easeOutCubic,
),
),
);
return FadeTransition(
opacity: animation,
child: SlideTransition(
position: slideAnimation,
child: PredictDeviceItemView(
device: widget.predictedAsset[itemIndex],
onPressed: (device) {
int? assetId = int.tryParse(device.assetId??'');
Navigator.of(context).pushNamed(AssetDetailPage.id, arguments:assetId );
},
),
),
);
},
)
: GridView.builder(
key: const ValueKey('grid_view'),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 12,
childAspectRatio: 1.5,
mainAxisSpacing: 12),
itemCount: widget.predictedAsset.length,
padding: const EdgeInsets.all(16),
itemBuilder: (context, index) {
// Calculate staggered animation delay
final delay = index * 0.08;
final animation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: _animationController,
curve: Interval(
delay.clamp(0.0, 0.8),
(delay + 0.3).clamp(0.0, 1.0),
curve: Curves.easeOut,
),
),
);
final slideAnimation = Tween<Offset>( final slideAnimation = Tween<Offset>(
begin: const Offset(0.0, 0.3), begin: const Offset(0.0, 0.15),
end: Offset.zero, end: Offset.zero,
).animate( ).animate(
CurvedAnimation( CurvedAnimation(
parent: _animationController, parent: _animationController,
curve: Interval( curve: Interval(
delay.clamp(0.0, 0.8), delay.clamp(0.0, 0.7),
(delay + 0.3).clamp(0.0, 1.0), (delay + 0.4).clamp(0.0, 1.0),
curve: Curves.easeOutCubic, curve: Curves.easeOutCubic,
), ),
), ),
); );
return FadeTransition( return FadeTransition(
opacity: animation, opacity: animation,
child: SlideTransition( child: SlideTransition(
position: slideAnimation, position: slideAnimation,
child: PredictDeviceItemGridView( child: PredictDeviceItemView(
device: widget.predictedAsset[index], device: widget.predictedAsset[itemIndex],
onPressed: (device) { onPressed: (device) {
//We are not getting asset id in response only have serial number int? assetId = int.tryParse(device.assetId ?? '');
int? assetId = int.tryParse(device.assetId??''); Navigator.of(context).pushNamed(AssetDetailPage.id, arguments: assetId);
Navigator.of(context).pushNamed(AssetDetailPage.id, arguments:assetId ); },
},
),
),
);
},
),
), ),
], ),
), );
); },
)));
} }
} }

Loading…
Cancel
Save