fixed token intilize

This commit is contained in:
mohamadmahdi jebeli 2025-07-31 11:47:41 +03:30
parent 0586fde872
commit 5d00779bbf
5 changed files with 403 additions and 249 deletions

View File

@ -1,3 +1,5 @@
// lib/main.dart
import 'dart:io'; import 'dart:io';
import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';

View File

@ -43,16 +43,80 @@ class _OffersPageState extends State<OffersPage> {
Timer? _locationTimer; Timer? _locationTimer;
bool _isSubscribedToOffers = false; bool _isSubscribedToOffers = false;
bool _isGpsEnabled = false; bool _isGpsEnabled = false;
bool _isConnectedToInternet = true;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_checkInitialConnectivity();
_initializePage(); _initializePage();
_initConnectivityListener(); _initConnectivityListener();
_fetchInitialReservations(); _fetchInitialReservations();
} }
@override
void dispose() {
_locationServiceSubscription?.cancel();
_mqttMessageSubscription?.cancel();
_locationTimer?.cancel();
_connectivitySubscription?.cancel();
super.dispose();
}
Future<void> _checkInitialConnectivity() async {
final connectivityResult = await Connectivity().checkConnectivity();
if (!mounted) return;
setState(() {
_isConnectedToInternet = !connectivityResult.contains(ConnectivityResult.none);
});
}
Future<void> _initializePage() async {
if (widget.showDialogsOnLoad) {
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (mounted) {
await showNotificationPermissionDialog(context);
await showGPSDialog(context);
}
});
}
await _loadPreferences();
_initLocationListener();
_subscribeToUserOffersOnLoad();
}
void _initConnectivityListener() {
_connectivitySubscription =
Connectivity().onConnectivityChanged.listen((results) {
final hasConnection = !results.contains(ConnectivityResult.none);
if (mounted && _isConnectedToInternet != hasConnection) {
setState(() {
_isConnectedToInternet = hasConnection;
});
if (hasConnection) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('اتصال به اینترنت برقرار شد.'),
backgroundColor: Colors.green,
),
);
} else {
context.read<OffersBloc>().add(ClearOffers());
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('اتصال به اینترنت قطع شد.'),
backgroundColor: Colors.red,
),
);
}
}
});
}
Future<void> _fetchInitialReservations() async { Future<void> _fetchInitialReservations() async {
if (!_isConnectedToInternet) return;
try { try {
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
final token = await storage.read(key: 'accessToken'); final token = await storage.read(key: 'accessToken');
@ -66,14 +130,11 @@ class _OffersPageState extends State<OffersPage> {
if (response.statusCode == 200 && mounted) { if (response.statusCode == 200 && mounted) {
final List<dynamic> reserves = response.data['reserves']; final List<dynamic> reserves = response.data['reserves'];
final List<String> reservedIds = final List<String> reservedIds = reserves
reserves .map((reserveData) =>
.map( (reserveData['Discount']['ID'] as String?) ?? '')
(reserveData) => .where((id) => id.isNotEmpty)
(reserveData['Discount']['ID'] as String?) ?? '', .toList();
)
.where((id) => id.isNotEmpty)
.toList();
context.read<ReservationCubit>().setReservedIds(reservedIds); context.read<ReservationCubit>().setReservedIds(reservedIds);
} }
@ -82,63 +143,6 @@ class _OffersPageState extends State<OffersPage> {
} }
} }
Future<void> _initializePage() async {
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (mounted) {
await showNotificationPermissionDialog(context);
await showGPSDialog(context);
}
});
await _loadPreferences();
_checkAndConnectMqtt();
_initLocationListener();
}
void _initConnectivityListener() {
_connectivitySubscription = Connectivity().onConnectivityChanged.listen((
List<ConnectivityResult> results,
) {
if (!results.contains(ConnectivityResult.none)) {
print(" Network connection restored.");
_checkAndConnectMqtt();
} else {
print(" Network connection lost.");
}
});
}
Future<void> _checkAndConnectMqtt() async {
final mqttService = context.read<MqttService>();
if (!mqttService.isConnected) {
print("--- OffersPage: MQTT not connected. Attempting to connect...");
final storage = const FlutterSecureStorage();
final token = await storage.read(key: 'accessToken');
if (token != null && token.isNotEmpty) {
try {
await mqttService.connect(token);
if (mqttService.isConnected && mounted) {
_subscribeToUserOffersOnLoad();
}
} catch (e) {
print("❌ OffersPage: Error connecting to MQTT: $e");
}
}
} else {
print("--- OffersPage: MQTT already connected.");
_subscribeToUserOffersOnLoad();
}
}
@override
void dispose() {
_locationServiceSubscription?.cancel();
_mqttMessageSubscription?.cancel();
_locationTimer?.cancel();
_connectivitySubscription?.cancel();
super.dispose();
}
Future<void> _subscribeToUserOffersOnLoad() async { Future<void> _subscribeToUserOffersOnLoad() async {
final storage = const FlutterSecureStorage(); final storage = const FlutterSecureStorage();
final userID = await storage.read(key: 'userID'); final userID = await storage.read(key: 'userID');
@ -149,22 +153,20 @@ class _OffersPageState extends State<OffersPage> {
void _initLocationListener() { void _initLocationListener() {
_checkInitialGpsStatus(); _checkInitialGpsStatus();
_locationServiceSubscription = Geolocator.getServiceStatusStream().listen(( _locationServiceSubscription =
status, Geolocator.getServiceStatusStream().listen((status) {
) {
final isEnabled = status == ServiceStatus.enabled; final isEnabled = status == ServiceStatus.enabled;
if (mounted && _isGpsEnabled != isEnabled) { if (mounted && _isGpsEnabled != isEnabled) {
setState(() { setState(() {
_isGpsEnabled = isEnabled; _isGpsEnabled = isEnabled;
}); });
} if (isEnabled) {
_startSendingLocationUpdates();
if (isEnabled) { } else {
_startSendingLocationUpdates(); debugPrint("❌ Location Service Disabled. Stopping updates.");
} else { _locationTimer?.cancel();
print("❌ Location Service Disabled. Stopping updates."); context.read<OffersBloc>().add(ClearOffers());
_locationTimer?.cancel(); }
context.read<OffersBloc>().add(ClearOffers());
} }
}); });
} }
@ -182,7 +184,7 @@ class _OffersPageState extends State<OffersPage> {
} }
void _startSendingLocationUpdates() { void _startSendingLocationUpdates() {
print("🚀 Starting periodic location updates."); debugPrint("🚀 Starting periodic location updates.");
_locationTimer?.cancel(); _locationTimer?.cancel();
_locationTimer = Timer.periodic(const Duration(seconds: 30), (timer) { _locationTimer = Timer.periodic(const Duration(seconds: 30), (timer) {
_sendLocationUpdate(); _sendLocationUpdate();
@ -191,9 +193,11 @@ class _OffersPageState extends State<OffersPage> {
} }
Future<void> _sendLocationUpdate() async { Future<void> _sendLocationUpdate() async {
if (!_isConnectedToInternet || !_isGpsEnabled) return;
final mqttService = context.read<MqttService>(); final mqttService = context.read<MqttService>();
if (!mqttService.isConnected) { if (!mqttService.isConnected) {
print("⚠️ MQTT not connected in OffersPage. Cannot send location."); debugPrint("⚠️ MQTT not connected in OffersPage. Cannot send location.");
return; return;
} }
@ -205,7 +209,7 @@ class _OffersPageState extends State<OffersPage> {
if (permission == LocationPermission.denied || if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) { permission == LocationPermission.deniedForever) {
print("🚫 Location permission denied by user."); debugPrint("🚫 Location permission denied by user.");
return; return;
} }
@ -217,15 +221,19 @@ class _OffersPageState extends State<OffersPage> {
final userID = await storage.read(key: 'userID'); final userID = await storage.read(key: 'userID');
if (userID == null) { if (userID == null) {
print("⚠️ UserID not found. Cannot send location."); debugPrint("⚠️ UserID not found. Cannot send location.");
return; return;
} }
final payload = {"userID": userID, "lat": 32.6685, "lng": 51.6826}; final payload = {
"userID": userID,
"lat":32.6685,
"lng": 51.6826
};
mqttService.publish("proxybuy/sendGps", payload); mqttService.publish("proxybuy/sendGps", payload);
} catch (e) { } catch (e) {
print("❌ Error sending location update in OffersPage: $e"); debugPrint("❌ Error sending location update in OffersPage: $e");
} }
} }
@ -233,6 +241,11 @@ class _OffersPageState extends State<OffersPage> {
if (_isSubscribedToOffers) return; if (_isSubscribedToOffers) return;
final mqttService = context.read<MqttService>(); final mqttService = context.read<MqttService>();
if (!mqttService.isConnected) {
debugPrint("⚠️ Cannot subscribe. MQTT client is not connected.");
return;
}
final topic = 'user-proxybuy/$userID'; final topic = 'user-proxybuy/$userID';
mqttService.subscribe(topic); mqttService.subscribe(topic);
_isSubscribedToOffers = true; _isSubscribedToOffers = true;
@ -240,28 +253,25 @@ class _OffersPageState extends State<OffersPage> {
_mqttMessageSubscription = mqttService.messages.listen((message) { _mqttMessageSubscription = mqttService.messages.listen((message) {
final data = message['data']; final data = message['data'];
if (data == null) { if (data == null || data is! List) {
if (mounted) { if (mounted) {
context.read<OffersBloc>().add(const OffersReceivedFromMqtt([])); context.read<OffersBloc>().add(const OffersReceivedFromMqtt([]));
} }
return; return;
} }
if (data is List) { try {
try { List<OfferModel> offers = data
List<OfferModel> offers = .whereType<Map<String, dynamic>>()
data .map((json) => OfferModel.fromJson(json))
.whereType<Map<String, dynamic>>() .toList();
.map((json) => OfferModel.fromJson(json))
.toList();
if (mounted) { if (mounted) {
context.read<OffersBloc>().add(OffersReceivedFromMqtt(offers)); context.read<OffersBloc>().add(OffersReceivedFromMqtt(offers));
}
} catch (e, stackTrace) {
print("❌ Error parsing offers from MQTT: $e");
print(stackTrace);
} }
} catch (e, stackTrace) {
debugPrint("❌ Error parsing offers from MQTT: $e");
debugPrint(stackTrace.toString());
} }
}); });
} }
@ -279,52 +289,52 @@ class _OffersPageState extends State<OffersPage> {
} }
Widget _buildFavoriteCategoriesSection() { Widget _buildFavoriteCategoriesSection() {
return Padding( return Padding(
padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0), padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
const Text( const Text(
'دسته‌بندی‌های مورد علاقه شما', 'دسته‌بندی‌های مورد علاقه شما',
style: TextStyle(fontSize: 19, fontWeight: FontWeight.bold), style: TextStyle(fontSize: 19, fontWeight: FontWeight.bold),
),
TextButton(
onPressed: () async {
await Navigator.of(context).push<bool>(
MaterialPageRoute(
builder: (context) => const NotificationPreferencesPage(
loadFavoritesOnStart: true,
),
),
);
if (!mounted) return;
context
.read<NotificationPreferencesBloc>()
.add(ResetSubmissionStatus());
_loadPreferences();
},
child: Row(
children: [
SvgPicture.asset(Assets.icons.edit.path),
const SizedBox(width: 4),
const Text(
'ویرایش',
style: TextStyle(color: AppColors.active),
),
],
), ),
), TextButton(
], onPressed: () async {
), await Navigator.of(context).push<bool>(
const Divider(height: 1), MaterialPageRoute(
const SizedBox(height: 12), builder: (context) => const NotificationPreferencesPage(
if (_selectedCategories.isEmpty) loadFavoritesOnStart: true,
),
),
);
if (!mounted) return;
context
.read<NotificationPreferencesBloc>()
.add(ResetSubmissionStatus());
_loadPreferences();
},
child: Row(
children: [
SvgPicture.asset(Assets.icons.edit.path),
const SizedBox(width: 4),
const Text(
'ویرایش',
style: TextStyle(color: AppColors.active),
),
],
),
),
],
),
const Divider(height: 1),
const SizedBox(height: 12),
if (_selectedCategories.isEmpty)
const Padding( const Padding(
padding: EdgeInsets.only(bottom: 8.0), padding: EdgeInsets.only(bottom: 8.0),
child: Text( child: Text(
@ -336,20 +346,19 @@ class _OffersPageState extends State<OffersPage> {
Wrap( Wrap(
spacing: 8.0, spacing: 8.0,
runSpacing: 8.0, runSpacing: 8.0,
children: children: _selectedCategories.map((category) {
_selectedCategories.map((category) { return Container(
return Container( padding: const EdgeInsets.symmetric(
padding: const EdgeInsets.symmetric( horizontal: 12.0,
horizontal: 12.0, vertical: 6.0,
vertical: 6.0, ),
), decoration: BoxDecoration(
decoration: BoxDecoration( border: Border.all(color: Colors.grey.shade300),
border: Border.all(color: Colors.grey.shade300), borderRadius: BorderRadius.circular(20.0),
borderRadius: BorderRadius.circular(20.0), ),
), child: Text(category),
child: Text(category), );
); }).toList(),
}).toList(),
), ),
], ],
), ),
@ -372,11 +381,11 @@ class _OffersPageState extends State<OffersPage> {
child: Assets.icons.logoWithName.svg(height: 40, width: 200), child: Assets.icons.logoWithName.svg(height: 40, width: 200),
), ),
actions: [ actions: [
IconButton(onPressed: () {}, icon: Assets.icons.notification.svg()), IconButton(
onPressed: () {}, icon: Assets.icons.notification.svg()),
BlocBuilder<ReservationCubit, ReservationState>( BlocBuilder<ReservationCubit, ReservationState>(
builder: (context, state) { builder: (context, state) {
final reservedCount = state.reservedProductIds.length; final reservedCount = state.reservedProductIds.length;
return Stack( return Stack(
alignment: Alignment.center, alignment: Alignment.center,
children: [ children: [
@ -407,10 +416,8 @@ class _OffersPageState extends State<OffersPage> {
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.green, color: Colors.green,
shape: BoxShape.circle, shape: BoxShape.circle,
border: Border.all( border:
color: Colors.white, Border.all(color: Colors.white, width: 1.5),
width: 1.5,
),
), ),
constraints: const BoxConstraints( constraints: const BoxConstraints(
minWidth: 18, minWidth: 18,
@ -443,7 +450,10 @@ class _OffersPageState extends State<OffersPage> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
_buildFavoriteCategoriesSection(), _buildFavoriteCategoriesSection(),
OffersView(isGpsEnabled: _isGpsEnabled), OffersView(
isGpsEnabled: _isGpsEnabled,
isConnectedToInternet: _isConnectedToInternet,
),
], ],
), ),
), ),
@ -454,17 +464,26 @@ class _OffersPageState extends State<OffersPage> {
class OffersView extends StatelessWidget { class OffersView extends StatelessWidget {
final bool isGpsEnabled; final bool isGpsEnabled;
final bool isConnectedToInternet;
const OffersView({super.key, required this.isGpsEnabled}); const OffersView({
super.key,
required this.isGpsEnabled,
required this.isConnectedToInternet,
});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (!isConnectedToInternet) {
return _buildNoInternetUI(context);
}
if (!isGpsEnabled) {
return _buildGpsActivationUI(context);
}
return BlocBuilder<OffersBloc, OffersState>( return BlocBuilder<OffersBloc, OffersState>(
builder: (context, state) { builder: (context, state) {
if (!isGpsEnabled) {
return _buildGpsActivationUI(context);
}
if (state is OffersInitial) { if (state is OffersInitial) {
return const SizedBox( return const SizedBox(
height: 300, height: 300,
@ -513,12 +532,10 @@ class OffersView extends StatelessWidget {
final offersForCategory = groupedOffers[category]!; final offersForCategory = groupedOffers[category]!;
return CategoryOffersRow( return CategoryOffersRow(
categoryTitle: category, categoryTitle: category,
offers: offersForCategory, offers: offersForCategory,
) ).animate().fade(duration: 500.ms).slideY(
.animate() begin: 0.3, duration: 400.ms, curve: Curves.easeOut);
.fade(duration: 500.ms)
.slideY(begin: 0.3, duration: 400.ms, curve: Curves.easeOut);
}, },
); );
} }
@ -578,4 +595,28 @@ class OffersView extends StatelessWidget {
), ),
); );
} }
Widget _buildNoInternetUI(BuildContext context) {
return SizedBox(
height: 300,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.wifi_off_rounded, size: 80, color: Colors.grey[400]),
const SizedBox(height: 20),
const Text(
"اتصال به اینترنت برقرار نیست",
style: TextStyle(fontSize: 18, color: Colors.grey),
),
const SizedBox(height: 10),
const Text(
"لطفاً اتصال خود را بررسی کرده و دوباره تلاش کنید.",
style: TextStyle(color: Colors.grey),
),
],
),
),
);
}
} }

View File

@ -657,23 +657,25 @@ class _ProductDetailViewState extends State<ProductDetailView> {
Localizations.override( Localizations.override(
context: context, context: context,
locale: const Locale('en'), locale: const Locale('en'),
child: SlideCountdown( child: Center(
duration: remainingDuration, child: SlideCountdown(
slideDirection: SlideDirection.up, duration: remainingDuration,
separator: ':', slideDirection: SlideDirection.up,
style: const TextStyle( separator: ':',
fontSize: 50, style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 50,
color: AppColors.countdown, fontWeight: FontWeight.bold,
color: AppColors.countdown,
),
separatorStyle: const TextStyle(
fontSize: 35,
color: AppColors.countdown,
),
decoration: const BoxDecoration(color: Colors.white),
shouldShowDays: (d) => d.inDays > 0,
shouldShowHours: (d) => d.inHours > 0,
shouldShowMinutes: (d) => d.inSeconds > 0,
), ),
separatorStyle: const TextStyle(
fontSize: 40,
color: AppColors.countdown,
),
decoration: const BoxDecoration(color: Colors.white),
shouldShowDays: (d) => d.inDays > 0,
shouldShowHours: (d) => d.inHours > 0,
shouldShowMinutes: (d) => d.inSeconds > 0,
), ),
), ),
const SizedBox(height: 4), const SizedBox(height: 4),

View File

@ -1,9 +1,10 @@
// lib/presentation/pages/splash_screen.dart
import 'dart:async'; import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:proxibuy/core/config/app_colors.dart';
import 'package:proxibuy/presentation/auth/bloc/auth_bloc.dart';
import 'package:proxibuy/presentation/pages/onboarding_page.dart'; import 'package:proxibuy/presentation/pages/onboarding_page.dart';
import 'package:proxibuy/presentation/pages/offers_page.dart'; import 'package:proxibuy/presentation/pages/offers_page.dart';
import 'package:proxibuy/core/gen/assets.gen.dart'; import 'package:proxibuy/core/gen/assets.gen.dart';
@ -17,65 +18,171 @@ class SplashScreen extends StatefulWidget {
} }
class _SplashScreenState extends State<SplashScreen> { class _SplashScreenState extends State<SplashScreen> {
bool _showRetryUI = false;
String _errorMessage = "";
bool _isChecking = true;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// با کمی تاخیر برای نمایش لوگو، فرآیند را شروع میکنیم Future.delayed(const Duration(seconds: 2), _startProcess);
Timer(const Duration(seconds: 2), _checkAuthAndNavigate);
} }
Future<void> _checkAuthAndNavigate() async { Future<void> _startProcess() async {
if (!mounted) return;
final hasInternet = await _checkInternet();
if (!hasInternet) {
setState(() {
_isChecking = false;
_showRetryUI = true;
_errorMessage = "اتصال به اینترنت برقرار نیست.";
});
return;
}
setState(() {
_isChecking = false;
});
}
Future<bool> _checkInternet() async {
final connectivityResult = await Connectivity().checkConnectivity();
return !connectivityResult.contains(ConnectivityResult.none);
}
Future<void> _connectAndNavigate() async {
if (!await _checkInternet()) {
setState(() {
_showRetryUI = true;
_errorMessage = "اتصال اینترنت قطع شد.";
});
return;
}
final mqttService = context.read<MqttService>();
final storage = const FlutterSecureStorage(); final storage = const FlutterSecureStorage();
final token = await storage.read(key: 'accessToken'); final token = await storage.read(key: 'accessToken');
if (token != null && token.isNotEmpty) { if (token != null && token.isNotEmpty) {
// کاربر احراز هویت شده است if (mqttService.isConnected) {
debugPrint("--- SplashScreen: User is authenticated. Connecting to MQTT..."); _navigateToOffers();
return;
}
try { try {
final mqttService = context.read<MqttService>(); await mqttService.connect(token).timeout(const Duration(seconds: 10));
// ۱. منتظر میمانیم تا اتصال کامل برقرار شود
await mqttService.connect(token);
// ۲. پس از اطمینان از اتصال، به صفحه بعد میرویم
if (mounted && mqttService.isConnected) { if (mounted && mqttService.isConnected) {
debugPrint("--- SplashScreen: MQTT Connected. Navigating to OffersPage."); _navigateToOffers();
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const OffersPage()),
);
} else if (mounted) { } else if (mounted) {
// اگر به هر دلیلی پس از اتمام متد، اتصال برقرار نبود setState(() {
debugPrint("--- SplashScreen: MQTT connection failed after attempt. Navigating to Onboarding."); _showRetryUI = true;
Navigator.of(context).pushReplacement( _errorMessage = "خطا در اتصال به سرور.";
MaterialPageRoute(builder: (_) => const OnboardingPage()), });
);
} }
} catch (e) { } catch (e) {
debugPrint("❌ SplashScreen: Critical error during MQTT connection: $e"); if (mounted) {
if (mounted) { setState(() {
Navigator.of(context).pushReplacement( _showRetryUI = true;
MaterialPageRoute(builder: (_) => const OnboardingPage()), _errorMessage = "خطای پیش‌بینی نشده در اتصال.";
); });
} }
} }
} else {
// کاربر احراز هویت نشده است
debugPrint("--- SplashScreen: User not authenticated. Navigating to Onboarding.");
if (mounted) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const OnboardingPage()),
);
}
} }
} }
void _navigateToOffers() {
if (!mounted) return;
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const OffersPage(showDialogsOnLoad: true)),
);
}
void _navigateToAuth() {
if (!mounted) return;
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const OnboardingPage()),
);
}
void _onRetry() {
setState(() {
_showRetryUI = false;
_errorMessage = "";
_isChecking = true;
});
_startProcess();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
backgroundColor: Colors.white, backgroundColor: Colors.white,
body: Center( body: BlocListener<AuthBloc, AuthState>(
child: Assets.icons.logo.svg(height: 160), listener: (context, state) {
if (_showRetryUI) return;
if (state is AuthSuccess) {
_connectAndNavigate();
} else if (state is AuthInitial || state is AuthFailure) {
_navigateToAuth();
}
},
child: Center(
child: _buildBody(),
),
),
);
}
Widget _buildBody() {
if (_showRetryUI) {
return _buildRetryWidget();
} else {
return _buildLogo();
}
}
Widget _buildLogo() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Assets.icons.logo.svg(height: 160),
if (_isChecking) ...[
const SizedBox(height: 32),
const CircularProgressIndicator(),
]
],
);
}
Widget _buildRetryWidget() {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.wifi_off_rounded, size: 80, color: Colors.grey.shade400),
const SizedBox(height: 24),
Text(
_errorMessage,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 18, color: Colors.black87, height: 1.5),
),
const SizedBox(height: 32),
ElevatedButton(
onPressed: _onRetry,
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.primary,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 12),
),
child: const Text(
"تلاش مجدد",
style: TextStyle(fontSize: 16),
),
)
],
), ),
); );
} }

View File

@ -7,7 +7,7 @@ import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart'; import 'package:mqtt_client/mqtt_server_client.dart';
class MqttService { class MqttService {
late MqttServerClient client; MqttServerClient? client;
final String server = '5.75.197.180'; final String server = '5.75.197.180';
final int port = 1883; final int port = 1883;
final StreamController<Map<String, dynamic>> _messageStreamController = final StreamController<Map<String, dynamic>> _messageStreamController =
@ -15,7 +15,9 @@ class MqttService {
Stream<Map<String, dynamic>> get messages => _messageStreamController.stream; Stream<Map<String, dynamic>> get messages => _messageStreamController.stream;
bool get isConnected => client.connectionStatus?.state == MqttConnectionState.connected; bool get isConnected {
return client?.connectionStatus?.state == MqttConnectionState.connected;
}
Future<void> connect(String token) async { Future<void> connect(String token) async {
final String clientId = final String clientId =
@ -24,10 +26,10 @@ class MqttService {
final String password = token; final String password = token;
client = MqttServerClient.withPort(server, clientId, port); client = MqttServerClient.withPort(server, clientId, port);
client.logging(on: true); client!.logging(on: true);
client.keepAlivePeriod = 60; client!.keepAlivePeriod = 60;
client.autoReconnect = true; client!.autoReconnect = true;
client.setProtocolV311(); client!.setProtocolV311();
debugPrint('--- [MQTT] Attempting to connect...'); debugPrint('--- [MQTT] Attempting to connect...');
debugPrint('--- [MQTT] Server: $server:$port'); debugPrint('--- [MQTT] Server: $server:$port');
@ -38,11 +40,11 @@ class MqttService {
.startClean() .startClean()
.authenticateAs(username, password); .authenticateAs(username, password);
client.connectionMessage = connMessage; client!.connectionMessage = connMessage;
client.onConnected = () { client!.onConnected = () {
debugPrint('✅ [MQTT] Connected successfully.'); debugPrint('✅ [MQTT] Connected successfully.');
client.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) { client!.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage; final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage;
final String payload = final String payload =
@ -62,43 +64,43 @@ class MqttService {
}); });
}; };
client.onDisconnected = () { client!.onDisconnected = () {
debugPrint('❌ [MQTT] Disconnected.'); debugPrint('❌ [MQTT] Disconnected.');
}; };
client.onAutoReconnect = () { client!.onAutoReconnect = () {
debugPrint('↪️ [MQTT] Auto-reconnecting...'); debugPrint('↪️ [MQTT] Auto-reconnecting...');
}; };
client.onAutoReconnected = () { client!.onAutoReconnected = () {
debugPrint('✅ [MQTT] Auto-reconnected successfully.'); debugPrint('✅ [MQTT] Auto-reconnected successfully.');
}; };
client.onSubscribed = (String topic) { client!.onSubscribed = (String topic) {
debugPrint('✅ [MQTT] Subscribed to topic: $topic'); debugPrint('✅ [MQTT] Subscribed to topic: $topic');
}; };
client.pongCallback = () { client!.pongCallback = () {
debugPrint('🏓 [MQTT] Ping response received'); debugPrint('🏓 [MQTT] Ping response received');
}; };
try { try {
await client.connect(); await client!.connect();
} on NoConnectionException catch (e) { } on NoConnectionException catch (e) {
debugPrint('❌ [MQTT] Connection failed - No Connection Exception: $e'); debugPrint('❌ [MQTT] Connection failed - No Connection Exception: $e');
client.disconnect(); client?.disconnect();
} on SocketException catch (e) { } on SocketException catch (e) {
debugPrint('❌ [MQTT] Connection failed - Socket Exception: $e'); debugPrint('❌ [MQTT] Connection failed - Socket Exception: $e');
client.disconnect(); client?.disconnect();
} catch (e) { } catch (e) {
debugPrint('❌ [MQTT] Connection failed - General Exception: $e'); debugPrint('❌ [MQTT] Connection failed - General Exception: $e');
client.disconnect(); client?.disconnect();
} }
} }
void subscribe(String topic) { void subscribe(String topic) {
if (isConnected) { if (isConnected) {
client.subscribe(topic, MqttQos.atLeastOnce); client?.subscribe(topic, MqttQos.atLeastOnce);
} else { } else {
debugPrint("⚠️ [MQTT] Cannot subscribe. Client is not connected."); debugPrint("⚠️ [MQTT] Cannot subscribe. Client is not connected.");
} }
@ -115,7 +117,7 @@ class MqttService {
debugPrint('>>>>> [MQTT] Payload: $payloadString'); debugPrint('>>>>> [MQTT] Payload: $payloadString');
debugPrint('>>>>> ======================= >>>>>'); debugPrint('>>>>> ======================= >>>>>');
client.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!); client?.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!);
} else { } else {
debugPrint("⚠️ [MQTT] Cannot publish. Client is not connected."); debugPrint("⚠️ [MQTT] Cannot publish. Client is not connected.");
} }
@ -124,6 +126,6 @@ class MqttService {
void dispose() { void dispose() {
debugPrint("--- [MQTT] Disposing MQTT Service."); debugPrint("--- [MQTT] Disposing MQTT Service.");
_messageStreamController.close(); _messageStreamController.close();
client.disconnect(); client?.disconnect();
} }
} }