قم باصلاح المشاكل في الكود واكمالة ليعمل ال foreground service الكود import…
- User
قم باصلاح المشاكل في الكود واكمالة ليعمل ال foreground service الكود import 'dart:async'; import 'dart:convert';
import 'package:flutter/material.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:http/http.dart' as http;
void main() { WidgetsFlutterBinding.ensureInitialized();
FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationChannelImportance.DEFAULT, priority: NotificationPriority.DEFAULT, ), iosNotificationOptions: const IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, eventAction: ForegroundTaskEventAction.repeat( const Duration(seconds: 1) as int, ), ), );
runApp(const MyApp()); }
class MyApp extends StatelessWidget { const MyApp({super.key});
@override Widget build(BuildContext context) { return MaterialApp( title: 'Network Monitor', theme: ThemeData( primarySwatch: Colors.blue, fontFamily: 'Tajawal', scaffoldBackgroundColor: const Color(0xFFF5F7FA), home: const LoginScreen(), debugShowCheckedModeBanner: false, ); } }
class LoginScreen extends StatefulWidget { const LoginScreen({super.key});
@override State createState() => _LoginScreenState(); }
class _LoginScreenState extends State { final _formKey = GlobalKey(); final _usernameController = TextEditingController(); final _passwordController = TextEditingController(); bool _isLoggingIn = false; bool _obscurePassword = true;
@override void dispose() { _usernameController.dispose(); _passwordController.dispose(); super.dispose(); }
Future _login() async { if (!_formKey.currentState!.validate()) return;
setState(() => _isLoggingIn = true); try { final response = await http .post( Uri.parse('http://172.16.0.1/login'), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: { 'username': _usernameController.text, 'password': _passwordController.text, }, ) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { final data = json.decode(response.body); if (data['status'] == 'success' && mounted) { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => DashboardScreen( username: _usernameController.text, userData: { 'username': _usernameController.text, 'ip': data['ip'] ?? 'غير معروف', 'mac': data['mac'] ?? 'غير معروف', }, ), ), ); } else { throw Exception(data['message'] ?? 'فشل تسجيل الدخول'); } } else { throw Exception('فشل الاتصال بالخادم'); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('حدث خطأ: ${e.toString()}'), backgroundColor: Colors.red, behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } } finally { if (mounted) setState(() => _isLoggingIn = false); }}
@override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.rtl, child: Scaffold( body: SafeArea( child: SingleChildScrollView( padding: const EdgeInsets.all(24.0), child: Column( children: [ const SizedBox(height: 40), Image.asset( 'assets/network_icon.png', // تأكد من إضافة الأيقونة في مجلد assets height: 120, width: 120, ), const SizedBox(height: 32), Text( 'مرحباً بعودتك', style: Theme.of(context).textTheme.headline5?.copyWith( fontWeight: FontWeight.bold, color: const Color(0xFF2E384D), ), ), const SizedBox(height: 8), Text( 'سجل الدخول للوصول إلى حسابك', style: Theme.of(context).textTheme.bodyText2?.copyWith( color: const Color(0xFF8798AD), ), const SizedBox(height: 32), Form( key: _formKey, child: Column( children: [ TextFormField( controller: _usernameController, decoration: InputDecoration( labelText: 'اسم المستخدم', prefixIcon: const Icon(Icons.person_outline_rounded, color: Color(0xFFB0BAC9)), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.isEmpty) { return 'الرجاء إدخال اسم المستخدم'; } return null; }, ), const SizedBox(height: 16), TextFormField( controller: _passwordController, obscureText: _obscurePassword, decoration: InputDecoration( labelText: 'كلمة المرور', prefixIcon: const Icon(Icons.lock_outline_rounded, color: Color(0xFFB0BAC9)), suffixIcon: IconButton( icon: Icon( _obscurePassword ? Icons.visibility_off_outlined : Icons.visibility_outlined, color: const Color(0xFFB0BAC9), ), onPressed: () { setState(() { _obscurePassword = !_obscurePassword; }); }, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.isEmpty) { return 'الرجاء إدخال كلمة المرور'; } return null; }, ), const SizedBox(height: 24), SizedBox( width: double.infinity, height: 50, child: ElevatedButton( onPressed: _isLoggingIn ? null : _login, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF3366FF), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), elevation: 0, shadowColor: Colors.transparent, ), child: _isLoggingIn ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Text( 'تسجيل الدخول', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ], ), ), ), ), ); } }
class DashboardScreen extends StatefulWidget { final String username; final Map<String, dynamic> userData;
const DashboardScreen({ super.key, required this.username, required this.userData, });
@override State createState() => _DashboardScreenState(); }
class _DashboardScreenState extends State with WidgetsBindingObserver { bool _isLoggingOut = false; Timer? _timer; late Map<String, dynamic> _currentUserData; bool _isForegroundServiceRunning = false;
@override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _currentUserData = widget.userData; _startPeriodicUpdate(); }
@override void dispose() { _timer?.cancel(); WidgetsBinding.instance.removeObserver(this); _stopForegroundService(); super.dispose(); }
@override void didChangeAppLifecycleState(AppLifecycleState state) { if (!mounted) return;
if (state == AppLifecycleState.paused) { _startForegroundService(); } else if (state == AppLifecycleState.resumed) { _stopForegroundService(); }}
Future _startForegroundService() async { if (_isForegroundServiceRunning) return;
await FlutterForegroundTask.startService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'جاري تحديث البيانات...', callback: startCallback, ); if (mounted) { setState(() => _isForegroundServiceRunning = true); }}
Future _stopForegroundService() async { await FlutterForegroundTask.stopService(); if (mounted) { setState(() => _isForegroundServiceRunning = false); } }
void _startPeriodicUpdate() { _timer = Timer.periodic(const Duration(seconds: 1), (timer) async { await _updateUserData(); }); }
Future _updateUserData() async { try { final response = await http .get(Uri.parse('http://172.16.0.1/status?var=json')) .timeout(const Duration(seconds: 10));
if (response.statusCode == 200) { final data = json.decode(response.body); if (data.containsKey('errors')) { return; } if (!mounted) return; setState(() { _currentUserData = { 'logged_in': data['logged_in'] ?? 'no', 'username': data['username'] ?? widget.username, 'mac': _decodeMacAddress(data['mac'] ?? ''), 'ip': data['ip'] ?? 'غير معروف', 'bytes_in': _formatBytes(data['bytes_in'] ?? '0'), 'bytes_out': _formatBytes(data['bytes_out'] ?? '0'), 'remain_bytes_total': _formatBytes( data['remain_bytes_total'] ?? '0', ), 'uptime': _formatUptimeExtended(data['uptime'] ?? '0s'), 'session_time_left': _formatSessionTimeLeft( data['session_time_left'] ?? 'غير محدود', ), }; }); if (_isForegroundServiceRunning) { FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'IP: ${_currentUserData['ip']} | المستلم: ${_currentUserData['bytes_in']} | المرسل: ${_currentUserData['bytes_out']} | المتبقي: ${_currentUserData['session_time_left']}', ); } } } catch (_) { if (_isForegroundServiceRunning) { FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'خطأ في تحديث البيانات', ); } }}
Future _logout() async { setState(() => _isLoggingOut = true);
try { await _stopForegroundService(); final response = await http .post( Uri.parse('http://172.16.0.1/logout'), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: {'username': widget.username}, ) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { if (mounted) { Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (_) => const LoginScreen()), (route) => false, ); } } else { throw Exception('فشل في تسجيل الخروج'); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('حدث خطأ: ${e.toString()}'), backgroundColor: Colors.red, behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } } finally { if (mounted) { setState(() => _isLoggingOut = false); } }}
String _decodeMacAddress(String encodedMac) { return encodedMac.replaceAll('%3A', ':'); }
String formatBytes(String bytes) { try { final value = int.parse(bytes); if (value < 1024) return '{(value / 1024).toStringAsFixed(1)} كيلوبايت'; if (value < 1024 * 1024 * 1024) return '{(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت'; } catch () { return bytes; } }
String _formatUptimeExtended(String uptime) { final regex = RegExp(r'(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?'); final match = regex.firstMatch(uptime); if (match == null) return uptime;
final days = int.tryParse(match.group(1) ?? '0') ?? 0; final hours = int.tryParse(match.group(2) ?? '0') ?? 0; final minutes = int.tryParse(match.group(3) ?? '0') ?? 0; final seconds = int.tryParse(match.group(4) ?? '0') ?? 0; String result = ''; if (days > 0) result += '$days يوم '; if (hours > 0) result += '$hours ساعة '; if (minutes > 0) result += '$minutes دقيقة '; if (seconds > 0) result += '$seconds ثانية'; return result.trim();}
String _formatSessionTimeLeft(String sessionTimeLeft) { if (sessionTimeLeft == 'غير محدود') return sessionTimeLeft; return _formatUptimeExtended(sessionTimeLeft); }
@override Widget build(BuildContext context) { return WithForegroundTask( child: Directionality( textDirection: TextDirection.rtl, child: Scaffold( backgroundColor: const Color(0xFFF5F7FA), appBar: AppBar( title: const Text('لوحة التحكم'), centerTitle: true, elevation: 0, backgroundColor: Colors.transparent, foregroundColor: const Color(0xFF2E384D), automaticallyImplyLeading: false, actions: [ IconButton( icon: const Icon(Icons.refresh_rounded), onPressed: _updateUserData, tooltip: 'تحديث البيانات', ), ], ), body: SafeArea( child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ _buildModernUserCard(context), const SizedBox(height: 24), Expanded( child: GridView.count( crossAxisCount: 2, childAspectRatio: 1.1, crossAxisSpacing: 16, mainAxisSpacing: 16, children: [ _buildModernStatCard( icon: Icons.timer_rounded, title: 'مدة الاتصال', value: _currentUserData['uptime'] ?? 'غير معروف', color: const Color(0xFF3366FF), ), _buildModernStatCard( icon: Icons.download_rounded, title: 'البيانات المستلمة', value: _currentUserData['bytes_in'] ?? '0', color: const Color(0xFF00C1D4), ), _buildModernStatCard( icon: Icons.upload_rounded, title: 'البيانات المرسلة', value: _currentUserData['bytes_out'] ?? '0', color: const Color(0xFFFF8A34), ), _buildModernStatCard( icon: Icons.access_time_filled_rounded, title: 'الوقت المتبقي', value: _currentUserData['session_time_left'] ?? 'غير محدود', color: const Color(0xFF50B83C), ), _buildModernStatCard( icon: Icons.data_usage_rounded, title: 'البيانات المتبقية', value: _currentUserData['remain_bytes_total'] ?? '0', color: const Color(0xFF9C6ADE), ), _buildModernStatCard( icon: Icons.network_check_rounded, title: 'حالة الاتصال', value: 'نشط', color: const Color(0xFFF7C948), ), ], ), ), const SizedBox(height: 16), SizedBox( width: double.infinity, child: ElevatedButton.icon( onPressed: _isLoggingOut ? null : _logout, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFFFF453A), foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(vertical: 16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), elevation: 0, ), icon: _isLoggingOut ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Icon(Icons.logout_rounded, size: 20), label: Text( _isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج', style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ), ), ), ); }
Widget _buildModernUserCard(BuildContext context) { return Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), color: Colors.white, boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.1), blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ Row( children: [ Container( width: 60, height: 60, decoration: BoxDecoration( color: const Color(0xFF3366FF).withOpacity(0.1), shape: BoxShape.circle, ), child: const Icon( Icons.person_rounded, size: 30, color: Color(0xFF3366FF), ), ), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _currentUserData['username'] ?? widget.username, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, fontFamily: 'Tajawal', color: Color(0xFF2E384D), ), maxLines: 1, overflow: TextOverflow.ellipsis, ), const SizedBox(height: 4), const Text( 'مستخدم Hotspot', style: TextStyle( fontSize: 14, color: Color(0xFF8798AD), fontFamily: 'Tajawal', ), ), ], ), ), ], ), const SizedBox(height: 16), Divider(color: Colors.grey.withOpacity(0.2), height: 1), const SizedBox(height: 12), _buildModernInfoRow( Icons.ip_rounded, 'عنوان IP:', _currentUserData['ip'] ?? 'غير معروف', const Color(0xFF2E384D), ), _buildModernInfoRow( Icons.device_hub_rounded, 'عنوان MAC:', _currentUserData['mac'] ?? 'غير معروف', const Color(0xFF2E384D), ), ], ), ), ); }
Widget _buildModernInfoRow( IconData icon, String label, String value, Color color, ) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: Row( children: [ Icon(icon, size: 20, color: color.withOpacity(0.6)), const SizedBox(width: 12), Text( label, style: TextStyle( fontWeight: FontWeight.bold, fontFamily: 'Tajawal', fontSize: 15, color: color.withOpacity(0.8), ), ), const SizedBox(width: 8), Expanded( child: Text( value, style: TextStyle( color: color, overflow: TextOverflow.ellipsis, fontFamily: 'Tajawal', ), ), ), ], ), ); }
Widget _buildModernStatCard({ required IconData icon, required String title, required String value, required Color color, }) { return Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(16), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.1), blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Padding( padding: const EdgeInsets.all(16), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: color.withOpacity(0.1), borderRadius: BorderRadius.circular(12), ), child: Icon(icon, size: 24, color: color), ), const SizedBox(height: 12), Text( value, style: const TextStyle( fontFamily: 'Tajawal', fontSize: 16, fontWeight: FontWeight.bold, color: Color(0xFF2E384D), ), ), const SizedBox(height: 4), Text( title, style: const TextStyle( fontFamily: 'Tajawal', fontSize: 13, color: Color(0xFF8798AD), ), ), ], ), ), ); } }
@pragma('vm:entry-point') void startCallback() { FlutterForegroundTask.setTaskHandler(NetworkStatusTaskHandler()); }
class NetworkStatusTaskHandler extends TaskHandler { @override Future onStart(DateTime timestamp, TaskStarter taskStarter) async { // إعدادات عند بدء الخدمة }
@override Future onEvent(DateTime timestamp) async { try { final response = await http .get(Uri.parse('http://172.16.0.1/status?var=json')) .timeout(const Duration(seconds: 10));
if (response.statusCode == 200) { final data = json.decode(response.body); if (data.containsKey('errors')) return; final username = data['username'] ?? 'غير معروف'; final ip = data['ip'] ?? 'غير معروف'; final bytesIn = _formatBytes(data['bytes_in'] ?? '0'); final bytesOut = _formatBytes(data['bytes_out'] ?? '0'); final sessionTimeLeft = data['session_time_left'] ?? 'غير محدود'; await FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - $username', notificationText: 'IP: $ip | المستلم: $bytesIn | المرسل: $bytesOut | المتبقي: $sessionTimeLeft', ); } } catch (_) { await FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة', notificationText: 'خطأ في تحديث البيانات', ); }}
@override void onRepeatEvent(DateTime timestamp) { // يمكنك ترك هذه فارغة أو تنفيذ مهام أخف إذا أردت، لكن لا يمكن استدعاء دوال async هنا }
@override Future onDestroy(DateTime timestamp, bool isOnMainThread) async { // تنظيف الموارد إذا لزم الأمر }
String formatBytes(String bytes) { try { final value = int.parse(bytes); if (value < 1024) return '{(value / 1024).toStringAsFixed(1)} كيلوبايت'; if (value < 1024 * 1024 * 1024) return '{(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت'; } catch () { return bytes; } } }
- Assistant
بالتأكيد، سأقوم بإصلاح المشاكل الموجودة في كودك، وتصحيح الاخطاء النحوية وتركيب الأوامر التي تمنع عمل الـforeground service بشكل صحيح، وتوفير نسخة كاملة تعمل بشكل جيد مع مكتبة
flutter_foreground_task.أبرز المشاكل التي وجدتُها:
- في استدعاء
ForegroundTaskEventAction.repeatتمرير المدة خاطئ (يجب تمريرDurationكلياً وليس تحويله إلىint). - في الدالة
mainلا تغلق قوس الـThemeDataبشكل صحيح (غالباً وجود{ناقص أو},بعدscaffoldBackgroundColor). - في
InputDecorationلبعض الحقول توجد أقواس غير مغلقةborderSide، وخاصةOutlineInputBorder. - في بعض الأماكن النقص في القوس أو فاصلة.
- عليك التأكد من أن
WithForegroundTaskيحتوي علىandroidNotificationOptions،iosNotificationOptions، وforegroundTaskOptions. - لم يتم استخدام نوع الـ callback عند بدء الخدمة مع الاسم الصحيح.
- يمكن تحسين بنية الكود قليلاً لتسهيل تتبعه.
الكود الكامل بعد التصحيح مع الشرح الضروري:
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:http/http.dart' as http; void main() async { WidgetsFlutterBinding.ensureInitialized(); await FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationChannelImportance.DEFAULT, priority: NotificationPriority.DEFAULT, iconData: const NotificationIconData( resType: ResourceType.mipmap, resPrefix: ResourcePrefix.ic, name: 'launcher', // تأكد من وجود هذا الأيقونة في android/app/src/main/res/mipmap ), ), iosNotificationOptions: const IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, // هنا التمرير الصحيح Duration دون تحويل ل int eventAction: ForegroundTaskEventAction.repeat( const Duration(seconds: 5), ), ), ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Network Monitor', theme: ThemeData( primarySwatch: Colors.blue, fontFamily: 'Tajawal', scaffoldBackgroundColor: const Color(0xFFF5F7FA), ), home: const LoginScreen(), debugShowCheckedModeBanner: false, ); } } class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); @override State<LoginScreen> createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { final _formKey = GlobalKey<FormState>(); final _usernameController = TextEditingController(); final _passwordController = TextEditingController(); bool _isLoggingIn = false; bool _obscurePassword = true; @override void dispose() { _usernameController.dispose(); _passwordController.dispose(); super.dispose(); } Future<void> _login() async { if (!_formKey.currentState!.validate()) return; setState(() => _isLoggingIn = true); try { final response = await http .post( Uri.parse('http://172.16.0.1/login'), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: { 'username': _usernameController.text, 'password': _passwordController.text, }, ) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { final data = json.decode(response.body); if (data['status'] == 'success' && mounted) { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => DashboardScreen( username: _usernameController.text, userData: { 'username': _usernameController.text, 'ip': data['ip'] ?? 'غير معروف', 'mac': data['mac'] ?? 'غير معروف', }, ), ), ); } else { throw Exception(data['message'] ?? 'فشل تسجيل الدخول'); } } else { throw Exception('فشل الاتصال بالخادم'); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('حدث خطأ: ${e.toString()}'), backgroundColor: Colors.red, behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } } finally { if (mounted) setState(() => _isLoggingIn = false); } } @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.rtl, child: Scaffold( body: SafeArea( child: SingleChildScrollView( padding: const EdgeInsets.all(24.0), child: Column( children: [ const SizedBox(height: 40), Image.asset( 'assets/network_icon.png', // تأكد من إضافة الأيقونة في مجلد assets وفي pubspec.yaml height: 120, width: 120, ), const SizedBox(height: 32), Text( 'مرحباً بعودتك', style: Theme.of(context).textTheme.headline5?.copyWith( fontWeight: FontWeight.bold, color: const Color(0xFF2E384D), ), ), const SizedBox(height: 8), Text( 'سجل الدخول للوصول إلى حسابك', style: Theme.of(context).textTheme.bodyText2?.copyWith( color: const Color(0xFF8798AD), ), ), const SizedBox(height: 32), Form( key: _formKey, child: Column( children: [ TextFormField( controller: _usernameController, decoration: InputDecoration( labelText: 'اسم المستخدم', prefixIcon: const Icon(Icons.person_outline_rounded, color: Color(0xFFB0BAC9)), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Color(0xFFE0E6ED)), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Color(0xFFE0E6ED)), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.isEmpty) { return 'الرجاء إدخال اسم المستخدم'; } return null; }, ), const SizedBox(height: 16), TextFormField( controller: _passwordController, obscureText: _obscurePassword, decoration: InputDecoration( labelText: 'كلمة المرور', prefixIcon: const Icon(Icons.lock_outline_rounded, color: Color(0xFFB0BAC9)), suffixIcon: IconButton( icon: Icon( _obscurePassword ? Icons.visibility_off_outlined : Icons.visibility_outlined, color: const Color(0xFFB0BAC9), ), onPressed: () { setState(() { _obscurePassword = !_obscurePassword; }); }, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Color(0xFFE0E6ED)), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Color(0xFFE0E6ED)), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.isEmpty) { return 'الرجاء إدخال كلمة المرور'; } return null; }, ), const SizedBox(height: 24), SizedBox( width: double.infinity, height: 50, child: ElevatedButton( onPressed: _isLoggingIn ? null : _login, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF3366FF), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), elevation: 0, shadowColor: Colors.transparent, ), child: _isLoggingIn ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Text( 'تسجيل الدخول', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ], ), ), ), ), ); } } class DashboardScreen extends StatefulWidget { final String username; final Map<String, dynamic> userData; const DashboardScreen({ super.key, required this.username, required this.userData, }); @override State<DashboardScreen> createState() => _DashboardScreenState(); } class _DashboardScreenState extends State<DashboardScreen> with WidgetsBindingObserver { bool _isLoggingOut = false; Timer? _timer; late Map<String, dynamic> _currentUserData; bool _isForegroundServiceRunning = false; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _currentUserData = widget.userData; _startPeriodicUpdate(); } @override void dispose() { _timer?.cancel(); WidgetsBinding.instance.removeObserver(this); _stopForegroundService(); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (!mounted) return; if (state == AppLifecycleState.paused) { _startForegroundService(); } else if (state == AppLifecycleState.resumed) { _stopForegroundService(); } } Future<void> _startForegroundService() async { if (_isForegroundServiceRunning) return; // تأكد من أنك لم تبدأ الخدمة مسبقاً await FlutterForegroundTask.startService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'جاري تحديث البيانات...', callback: startCallback, ); if (mounted) { setState(() => _isForegroundServiceRunning = true); } } Future<void> _stopForegroundService() async { await FlutterForegroundTask.stopService(); if (mounted) { setState(() => _isForegroundServiceRunning = false); } } void _startPeriodicUpdate() { _timer = Timer.periodic(const Duration(seconds: 5), (timer) async { await _updateUserData(); }); } Future<void> _updateUserData() async { try { final response = await http .get(Uri.parse('http://172.16.0.1/status?var=json')) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { final data = json.decode(response.body); if (data.containsKey('errors')) { return; } if (!mounted) return; setState(() { _currentUserData = { 'logged_in': data['logged_in'] ?? 'no', 'username': data['username'] ?? widget.username, 'mac': _decodeMacAddress(data['mac'] ?? ''), 'ip': data['ip'] ?? 'غير معروف', 'bytes_in': _formatBytes(data['bytes_in'] ?? '0'), 'bytes_out': _formatBytes(data['bytes_out'] ?? '0'), 'remain_bytes_total': _formatBytes( data['remain_bytes_total'] ?? '0', ), 'uptime': _formatUptimeExtended(data['uptime'] ?? '0s'), 'session_time_left': _formatSessionTimeLeft( data['session_time_left'] ?? 'غير محدود', ), }; }); if (_isForegroundServiceRunning) { FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'IP: ${_currentUserData['ip']} | المستلم: ${_currentUserData['bytes_in']} | المرسل: ${_currentUserData['bytes_out']} | المتبقي: ${_currentUserData['session_time_left']}', ); } } } catch (_) { if (_isForegroundServiceRunning) { FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'خطأ في تحديث البيانات', ); } } } Future<void> _logout() async { setState(() => _isLoggingOut = true); try { await _stopForegroundService(); final response = await http .post( Uri.parse('http://172.16.0.1/logout'), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: {'username': widget.username}, ) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { if (mounted) { Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (_) => const LoginScreen()), (route) => false, ); } } else { throw Exception('فشل في تسجيل الخروج'); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('حدث خطأ: ${e.toString()}'), backgroundColor: Colors.red, behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } } finally { if (mounted) { setState(() => _isLoggingOut = false); } } } String _decodeMacAddress(String encodedMac) { return encodedMac.replaceAll('%3A', ':'); } String _formatBytes(String bytes) { try { final value = int.parse(bytes); if (value < 1024) return '$value بايت'; if (value < 1024 * 1024) return '${(value / 1024).toStringAsFixed(1)} كيلوبايت'; if (value < 1024 * 1024 * 1024) return '${(value / (1024 * 1024)).toStringAsFixed(1)} ميجابايت'; return '${(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت'; } catch (_) { return bytes; } } String _formatUptimeExtended(String uptime) { final regex = RegExp(r'(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?'); final match = regex.firstMatch(uptime); if (match == null) return uptime; final days = int.tryParse(match.group(1) ?? '0') ?? 0; final hours = int.tryParse(match.group(2) ?? '0') ?? 0; final minutes = int.tryParse(match.group(3) ?? '0') ?? 0; final seconds = int.tryParse(match.group(4) ?? '0') ?? 0; String result = ''; if (days > 0) result += '$days يوم '; if (hours > 0) result += '$hours ساعة '; if (minutes > 0) result += '$minutes دقيقة '; if (seconds > 0) result += '$seconds ثانية'; return result.trim(); } String _formatSessionTimeLeft(String sessionTimeLeft) { if (sessionTimeLeft == 'غير محدود') return sessionTimeLeft; return _formatUptimeExtended(sessionTimeLeft); } @override Widget build(BuildContext context) { return WithForegroundTask( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationChannelImportance.DEFAULT, priority: NotificationPriority.DEFAULT, iconData: const NotificationIconData( resType: ResourceType.mipmap, resPrefix: ResourcePrefix.ic, name: 'launcher', ), ), iosNotificationOptions: const IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: const ForegroundTaskOptions( allowWakeLock: true, allowWifiLock: true, autoRunOnBoot: false, eventInterval: 5000, ), child: Directionality( textDirection: TextDirection.rtl, child: Scaffold( backgroundColor: const Color(0xFFF5F7FA), appBar: AppBar( title: const Text('لوحة التحكم'), centerTitle: true, elevation: 0, backgroundColor: Colors.transparent, foregroundColor: const Color(0xFF2E384D), automaticallyImplyLeading: false, actions: [ IconButton( icon: const Icon(Icons.refresh_rounded), onPressed: _updateUserData, tooltip: 'تحديث البيانات', ), ], ), body: SafeArea( child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ _buildModernUserCard(context), const SizedBox(height: 24), Expanded( child: GridView.count( crossAxisCount: 2, childAspectRatio: 1.1, crossAxisSpacing: 16, mainAxisSpacing: 16, children: [ _buildModernStatCard( icon: Icons.timer_rounded, title: 'مدة الاتصال', value: _currentUserData['uptime'] ?? 'غير معروف', color: const Color(0xFF3366FF), ), _buildModernStatCard( icon: Icons.download_rounded, title: 'البيانات المستلمة', value: _currentUserData['bytes_in'] ?? '0', color: const Color(0xFF00C1D4), ), _buildModernStatCard( icon: Icons.upload_rounded, title: 'البيانات المرسلة', value: _currentUserData['bytes_out'] ?? '0', color: const Color(0xFFFF8A34), ), _buildModernStatCard( icon: Icons.access_time_filled_rounded, title: 'الوقت المتبقي', value: _currentUserData['session_time_left'] ?? 'غير محدود', color: const Color(0xFF50B83C), ), _buildModernStatCard( icon: Icons.data_usage_rounded, title: 'البيانات المتبقية', value: _currentUserData['remain_bytes_total'] ?? '0', color: const Color(0xFF9C6ADE), ), _buildModernStatCard( icon: Icons.network_check_rounded, title: 'حالة الاتصال', value: 'نشط', color: const Color(0xFFF7C948), ), ], ), ), const SizedBox(height: 16), SizedBox( width: double.infinity, child: ElevatedButton.icon( onPressed: _isLoggingOut ? null : _logout, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFFFF453A), foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(vertical: 16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), elevation: 0, ), icon: _isLoggingOut ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Icon(Icons.logout_rounded, size: 20), label: Text( _isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج', style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ), ), ), ); } Widget _buildModernUserCard(BuildContext context) { return Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), color: Colors.white, boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.1), blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ Row( children: [ Container( width: 60, height: 60, decoration: BoxDecoration( color: const Color(0xFF3366FF).withOpacity(0.1), shape: BoxShape.circle, ), child: const Icon( Icons.person_rounded, size: 30, color: Color(0xFF3366FF), ), ), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _currentUserData['username'] ?? widget.username, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, fontFamily: 'Tajawal', color: Color(0xFF2E384D), ), maxLines: 1, overflow: TextOverflow.ellipsis, ), const SizedBox(height: 4), const Text( 'مستخدم Hotspot', style: TextStyle( fontSize: 14, color: Color(0xFF8798AD), fontFamily: 'Tajawal', ), ), ], ), ), ], ), const SizedBox(height: 16), Divider(color: Colors.grey.withOpacity(0.2), height: 1), const SizedBox(height: 12), _buildModernInfoRow( Icons.ip_rounded, 'عنوان IP:', _currentUserData['ip'] ?? 'غير معروف', const Color(0xFF2E384D), ), _buildModernInfoRow( Icons.device_hub_rounded, 'عنوان MAC:', _currentUserData['mac'] ?? 'غير معروف', const Color(0xFF2E384D), ), ], ), ), ); } Widget _buildModernInfoRow( IconData icon, String label, String value, Color color, ) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: Row( children: [ Icon(icon, size: 20, color: color.withOpacity(0.6)), const SizedBox(width: 12), Text( label, style: TextStyle( fontWeight: FontWeight.bold, fontFamily: 'Tajawal', fontSize: 15, color: color.withOpacity(0.8), ), ), const SizedBox(width: 8), Expanded( child: Text( value, style: TextStyle( color: color, overflow: TextOverflow.ellipsis, fontFamily: 'Tajawal', ), ), ), ], ), ); } Widget _buildModernStatCard({ required IconData icon, required String title, required String value, required Color color, }) { return Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(16), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.1), blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Padding( padding: const EdgeInsets.all(16), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: color.withOpacity(0.1), borderRadius: BorderRadius.circular(12), ), child: Icon(icon, size: 24, color: color), ), const SizedBox(height: 12), Text( value, style: const TextStyle( fontFamily: 'Tajawal', fontSize: 16, fontWeight: FontWeight.bold, color: Color(0xFF2E384D), ), ), const SizedBox(height: 4), Text( title, style: const TextStyle( fontFamily: 'Tajawal', fontSize: 13, color: Color(0xFF8798AD), ), ), ], ), ), ); } } @pragma('vm:entry-point') void startCallback() { FlutterForegroundTask.setTaskHandler(NetworkStatusTaskHandler()); } class NetworkStatusTaskHandler extends TaskHandler { @override Future<void> onStart(DateTime timestamp, TaskStarter taskStarter) async { // إعدادات عند بدء الخدمة } @override Future<void> onEvent(DateTime timestamp) async { try { final response = await http .get(Uri.parse('http://172.16.0.1/status?var=json')) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { final data = json.decode(response.body); if (data.containsKey('errors')) return; final username = data['username'] ?? 'غير معروف'; final ip = data['ip'] ?? 'غير معروف'; final bytesIn = _formatBytes(data['bytes_in'] ?? '0'); final bytesOut = _formatBytes(data['bytes_out'] ?? '0'); final sessionTimeLeft = data['session_time_left'] ?? 'غير محدود'; await FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - $username', notificationText: 'IP: $ip | المستلم: $bytesIn | المرسل: $bytesOut | المتبقي: $sessionTimeLeft', ); } } catch (_) { await FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة', notificationText: 'خطأ في تحديث البيانات', ); } } @override void onRepeatEvent(DateTime timestamp) { // يمكن تركها فارغة أو إعداد مهام خفيفة (غير async) } @override Future<void> onDestroy(DateTime timestamp, bool isOnMainThread) async { // تنظيف الموارد إذا لزم الأمر } String _formatBytes(String bytes) { try { final value = int.parse(bytes); if (value < 1024) return '$value بايت'; if (value < 1024 * 1024) return '${(value / 1024).toStringAsFixed(1)} كيلوبايت'; if (value < 1024 * 1024 * 1024) return '${(value / (1024 * 1024)).toStringAsFixed(1)} ميجابايت'; return '${(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت'; } catch (_) { return bytes; } } }
نصائح إضافية:
- تأكد من إضافة الأيقونة الصحيحة في مجلد الموارد لـ android.
- في ملف
android/app/src/main/AndroidManifest.xmlيجب إضافة الصلاحيات اللازمة للـ foreground service:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.WAKE_LOCK" />- تأكد من أن لديك إعدادات بروكسي أو شبكة صحيحة للتواصل مع العنوان
http://172.16.0.1/. - يمكنك التحكم بفترات تحديث الإشعار وخدمة الـ foreground عبر تعديل
eventIntervalفيForegroundTaskOptionsأو في التايمر في الشاشة.
إذا واجهت أي مشكلة أخرى أو تحتاج شرحًا لأجزاء محددة، يسعدني المساعدة!
- في استدعاء
- User
صحح الكود يوجد فية الكثر من المشاكل import 'dart:async'; import 'dart:convert';
import 'package:flutter/material.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:http/http.dart' as http;
void main() async { WidgetsFlutterBinding.ensureInitialized();
await FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationChannelImportance.DEFAULT, priority: NotificationPriority.DEFAULT, iconData: const NotificationIconData( resType: ResourceType.mipmap, resPrefix: ResourcePrefix.ic, name: 'launcher', // تأكد من وجود هذا الأيقونة في android/app/src/main/res/mipmap ), ), iosNotificationOptions: const IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, // هنا التمرير الصحيح Duration دون تحويل ل int eventAction: ForegroundTaskEventAction.repeat(const Duration(seconds: 5)), ), );
runApp(const MyApp()); }
class MyApp extends StatelessWidget { const MyApp({super.key});
@override Widget build(BuildContext context) { return MaterialApp( title: 'Network Monitor', theme: ThemeData( primarySwatch: Colors.blue, fontFamily: 'Tajawal', scaffoldBackgroundColor: const Color(0xFFF5F7FA), ), home: const LoginScreen(), debugShowCheckedModeBanner: false, ); } }
class LoginScreen extends StatefulWidget { const LoginScreen({super.key});
@override State createState() => _LoginScreenState(); }
class _LoginScreenState extends State { final _formKey = GlobalKey(); final _usernameController = TextEditingController(); final _passwordController = TextEditingController(); bool _isLoggingIn = false; bool _obscurePassword = true;
@override void dispose() { _usernameController.dispose(); _passwordController.dispose(); super.dispose(); }
Future _login() async { if (!_formKey.currentState!.validate()) return;
setState(() => _isLoggingIn = true); try { final response = await http .post( Uri.parse('http://172.16.0.1/login'), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: { 'username': _usernameController.text, 'password': _passwordController.text, }, ) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { final data = json.decode(response.body); if (data['status'] == 'success' && mounted) { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => DashboardScreen( username: _usernameController.text, userData: { 'username': _usernameController.text, 'ip': data['ip'] ?? 'غير معروف', 'mac': data['mac'] ?? 'غير معروف', }, ), ), ); } else { throw Exception(data['message'] ?? 'فشل تسجيل الدخول'); } } else { throw Exception('فشل الاتصال بالخادم'); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('حدث خطأ: ${e.toString()}'), backgroundColor: Colors.red, behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } } finally { if (mounted) setState(() => _isLoggingIn = false); }}
@override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.rtl, child: Scaffold( body: SafeArea( child: SingleChildScrollView( padding: const EdgeInsets.all(24.0), child: Column( children: [ const SizedBox(height: 40), Image.asset( 'assets/network_icon.png', // تأكد من إضافة الأيقونة في مجلد assets وفي pubspec.yaml height: 120, width: 120, ), const SizedBox(height: 32), Text( 'مرحباً بعودتك', style: Theme.of(context).textTheme.headlineSmall?.copyWith( fontWeight: FontWeight.bold, color: const Color(0xFF2E384D), ), ), const SizedBox(height: 8), Text( 'سجل الدخول للوصول إلى حسابك', style: Theme.of(context).textTheme.bodyMedium?.copyWith( color: const Color(0xFF8798AD), ), ), const SizedBox(height: 32), Form( key: _formKey, child: Column( children: [ TextFormField( controller: _usernameController, decoration: InputDecoration( labelText: 'اسم المستخدم', prefixIcon: const Icon( Icons.person_outline_rounded, color: Color(0xFFB0BAC9), ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.isEmpty) { return 'الرجاء إدخال اسم المستخدم'; } return null; }, ), const SizedBox(height: 16), TextFormField( controller: _passwordController, obscureText: _obscurePassword, decoration: InputDecoration( labelText: 'كلمة المرور', prefixIcon: const Icon( Icons.lock_outline_rounded, color: Color(0xFFB0BAC9), ), suffixIcon: IconButton( icon: Icon( _obscurePassword ? Icons.visibility_off_outlined : Icons.visibility_outlined, color: const Color(0xFFB0BAC9), ), onPressed: () { setState(() { _obscurePassword = !_obscurePassword; }); }, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.isEmpty) { return 'الرجاء إدخال كلمة المرور'; } return null; }, ), const SizedBox(height: 24), SizedBox( width: double.infinity, height: 50, child: ElevatedButton( onPressed: _isLoggingIn ? null : _login, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF3366FF), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), elevation: 0, shadowColor: Colors.transparent, ), child: _isLoggingIn ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Text( 'تسجيل الدخول', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ], ), ), ), ), ); } }
class DashboardScreen extends StatefulWidget { final String username; final Map<String, dynamic> userData;
const DashboardScreen({ super.key, required this.username, required this.userData, });
@override State createState() => _DashboardScreenState(); }
class _DashboardScreenState extends State with WidgetsBindingObserver { bool _isLoggingOut = false; Timer? _timer; late Map<String, dynamic> _currentUserData; bool _isForegroundServiceRunning = false;
@override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _currentUserData = widget.userData; _startPeriodicUpdate(); }
@override void dispose() { _timer?.cancel(); WidgetsBinding.instance.removeObserver(this); _stopForegroundService(); super.dispose(); }
@override void didChangeAppLifecycleState(AppLifecycleState state) { if (!mounted) return;
if (state == AppLifecycleState.paused) { _startForegroundService(); } else if (state == AppLifecycleState.resumed) { _stopForegroundService(); }}
Future _startForegroundService() async { if (_isForegroundServiceRunning) return;
// تأكد من أنك لم تبدأ الخدمة مسبقاً await FlutterForegroundTask.startService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'جاري تحديث البيانات...', callback: startCallback, ); if (mounted) { setState(() => _isForegroundServiceRunning = true); }}
Future _stopForegroundService() async { await FlutterForegroundTask.stopService(); if (mounted) { setState(() => _isForegroundServiceRunning = false); } }
void _startPeriodicUpdate() { _timer = Timer.periodic(const Duration(seconds: 5), (timer) async { await _updateUserData(); }); }
Future _updateUserData() async { try { final response = await http .get(Uri.parse('http://172.16.0.1/status?var=json')) .timeout(const Duration(seconds: 10));
if (response.statusCode == 200) { final data = json.decode(response.body); if (data.containsKey('errors')) { return; } if (!mounted) return; setState(() { _currentUserData = { 'logged_in': data['logged_in'] ?? 'no', 'username': data['username'] ?? widget.username, 'mac': _decodeMacAddress(data['mac'] ?? ''), 'ip': data['ip'] ?? 'غير معروف', 'bytes_in': _formatBytes(data['bytes_in'] ?? '0'), 'bytes_out': _formatBytes(data['bytes_out'] ?? '0'), 'remain_bytes_total': _formatBytes( data['remain_bytes_total'] ?? '0', ), 'uptime': _formatUptimeExtended(data['uptime'] ?? '0s'), 'session_time_left': _formatSessionTimeLeft( data['session_time_left'] ?? 'غير محدود', ), }; }); if (_isForegroundServiceRunning) { FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'IP: ${_currentUserData['ip']} | المستلم: ${_currentUserData['bytes_in']} | المرسل: ${_currentUserData['bytes_out']} | المتبقي: ${_currentUserData['session_time_left']}', ); } } } catch (_) { if (_isForegroundServiceRunning) { FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'خطأ في تحديث البيانات', ); } }}
Future _logout() async { setState(() => _isLoggingOut = true);
try { await _stopForegroundService(); final response = await http .post( Uri.parse('http://172.16.0.1/logout'), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: {'username': widget.username}, ) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { if (mounted) { Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (_) => const LoginScreen()), (route) => false, ); } } else { throw Exception('فشل في تسجيل الخروج'); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('حدث خطأ: ${e.toString()}'), backgroundColor: Colors.red, behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } } finally { if (mounted) { setState(() => _isLoggingOut = false); } }}
String _decodeMacAddress(String encodedMac) { return encodedMac.replaceAll('%3A', ':'); }
String formatBytes(String bytes) { try { final value = int.parse(bytes); if (value < 1024) return '{(value / 1024).toStringAsFixed(1)} كيلوبايت'; if (value < 1024 * 1024 * 1024) return '{(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت'; } catch () { return bytes; } }
String _formatUptimeExtended(String uptime) { final regex = RegExp(r'(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?'); final match = regex.firstMatch(uptime); if (match == null) return uptime;
final days = int.tryParse(match.group(1) ?? '0') ?? 0; final hours = int.tryParse(match.group(2) ?? '0') ?? 0; final minutes = int.tryParse(match.group(3) ?? '0') ?? 0; final seconds = int.tryParse(match.group(4) ?? '0') ?? 0; String result = ''; if (days > 0) result += '$days يوم '; if (hours > 0) result += '$hours ساعة '; if (minutes > 0) result += '$minutes دقيقة '; if (seconds > 0) result += '$seconds ثانية'; return result.trim();}
String _formatSessionTimeLeft(String sessionTimeLeft) { if (sessionTimeLeft == 'غير محدود') return sessionTimeLeft; return _formatUptimeExtended(sessionTimeLeft); }
@override Widget build(BuildContext context) { return WithForegroundTask( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationChannelImportance.DEFAULT, priority: NotificationPriority.DEFAULT, iconData: const NotificationIconData( resType: ResourceType.mipmap, resPrefix: ResourcePrefix.ic, name: 'launcher', ), ), iosNotificationOptions: const IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: const ForegroundTaskOptions( allowWakeLock: true, allowWifiLock: true, autoRunOnBoot: false, eventInterval: 5000, ), child: Directionality( textDirection: TextDirection.rtl, child: Scaffold( backgroundColor: const Color(0xFFF5F7FA), appBar: AppBar( title: const Text('لوحة التحكم'), centerTitle: true, elevation: 0, backgroundColor: Colors.transparent, foregroundColor: const Color(0xFF2E384D), automaticallyImplyLeading: false, actions: [ IconButton( icon: const Icon(Icons.refresh_rounded), onPressed: _updateUserData, tooltip: 'تحديث البيانات', ), ], ), body: SafeArea( child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ _buildModernUserCard(context), const SizedBox(height: 24), Expanded( child: GridView.count( crossAxisCount: 2, childAspectRatio: 1.1, crossAxisSpacing: 16, mainAxisSpacing: 16, children: [ _buildModernStatCard( icon: Icons.timer_rounded, title: 'مدة الاتصال', value: _currentUserData['uptime'] ?? 'غير معروف', color: const Color(0xFF3366FF), ), _buildModernStatCard( icon: Icons.download_rounded, title: 'البيانات المستلمة', value: _currentUserData['bytes_in'] ?? '0', color: const Color(0xFF00C1D4), ), _buildModernStatCard( icon: Icons.upload_rounded, title: 'البيانات المرسلة', value: _currentUserData['bytes_out'] ?? '0', color: const Color(0xFFFF8A34), ), _buildModernStatCard( icon: Icons.access_time_filled_rounded, title: 'الوقت المتبقي', value: _currentUserData['session_time_left'] ?? 'غير محدود', color: const Color(0xFF50B83C), ), _buildModernStatCard( icon: Icons.data_usage_rounded, title: 'البيانات المتبقية', value: _currentUserData['remain_bytes_total'] ?? '0', color: const Color(0xFF9C6ADE), ), _buildModernStatCard( icon: Icons.network_check_rounded, title: 'حالة الاتصال', value: 'نشط', color: const Color(0xFFF7C948), ), ], ), ), const SizedBox(height: 16), SizedBox( width: double.infinity, child: ElevatedButton.icon( onPressed: _isLoggingOut ? null : _logout, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFFFF453A), foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(vertical: 16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), elevation: 0, ), icon: _isLoggingOut ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Icon(Icons.logout_rounded, size: 20), label: Text( _isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج', style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ), ), ), ); }
Widget _buildModernUserCard(BuildContext context) { return Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), color: Colors.white, boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.1), blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ Row( children: [ Container( width: 60, height: 60, decoration: BoxDecoration( color: const Color(0xFF3366FF).withOpacity(0.1), shape: BoxShape.circle, ), child: const Icon( Icons.person_rounded, size: 30, color: Color(0xFF3366FF), ), ), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _currentUserData['username'] ?? widget.username, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, fontFamily: 'Tajawal', color: Color(0xFF2E384D), ), maxLines: 1, overflow: TextOverflow.ellipsis, ), const SizedBox(height: 4), const Text( 'مستخدم Hotspot', style: TextStyle( fontSize: 14, color: Color(0xFF8798AD), fontFamily: 'Tajawal', ), ), ], ), ), ], ), const SizedBox(height: 16), Divider(color: Colors.grey.withOpacity(0.2), height: 1), const SizedBox(height: 12), _buildModernInfoRow( Icons.mp_rounded, 'عنوان IP:', _currentUserData['ip'] ?? 'غير معروف', const Color(0xFF2E384D), ), _buildModernInfoRow( Icons.device_hub_rounded, 'عنوان MAC:', _currentUserData['mac'] ?? 'غير معروف', const Color(0xFF2E384D), ), ], ), ), ); }
Widget _buildModernInfoRow( IconData icon, String label, String value, Color color, ) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: Row( children: [ Icon(icon, size: 20, color: color.withOpacity(0.6)), const SizedBox(width: 12), Text( label, style: TextStyle( fontWeight: FontWeight.bold, fontFamily: 'Tajawal', fontSize: 15, color: color.withOpacity(0.8), ), ), const SizedBox(width: 8), Expanded( child: Text( value, style: TextStyle( color: color, overflow: TextOverflow.ellipsis, fontFamily: 'Tajawal', ), ), ), ], ), ); }
Widget _buildModernStatCard({ required IconData icon, required String title, required String value, required Color color, }) { return Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(16), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.1), blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Padding( padding: const EdgeInsets.all(16), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: color.withOpacity(0.1), borderRadius: BorderRadius.circular(12), ), child: Icon(icon, size: 24, color: color), ), const SizedBox(height: 12), Text( value, style: const TextStyle( fontFamily: 'Tajawal', fontSize: 16, fontWeight: FontWeight.bold, color: Color(0xFF2E384D), ), ), const SizedBox(height: 4), Text( title, style: const TextStyle( fontFamily: 'Tajawal', fontSize: 13, color: Color(0xFF8798AD), ), ), ], ), ), ); } }
@pragma('vm:entry-point') void startCallback() { FlutterForegroundTask.setTaskHandler(NetworkStatusTaskHandler()); }
class NetworkStatusTaskHandler extends TaskHandler { @override Future onStart(DateTime timestamp, TaskStarter taskStarter) async { // إعدادات عند بدء الخدمة }
@override Future onEvent(DateTime timestamp) async { try { final response = await http .get(Uri.parse('http://172.16.0.1/status?var=json')) .timeout(const Duration(seconds: 10));
if (response.statusCode == 200) { final data = json.decode(response.body); if (data.containsKey('errors')) return; final username = data['username'] ?? 'غير معروف'; final ip = data['ip'] ?? 'غير معروف'; final bytesIn = _formatBytes(data['bytes_in'] ?? '0'); final bytesOut = _formatBytes(data['bytes_out'] ?? '0'); final sessionTimeLeft = data['session_time_left'] ?? 'غير محدود'; await FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - $username', notificationText: 'IP: $ip | المستلم: $bytesIn | المرسل: $bytesOut | المتبقي: $sessionTimeLeft', ); } } catch (_) { await FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة', notificationText: 'خطأ في تحديث البيانات', ); }}
@override void onRepeatEvent(DateTime timestamp) { // يمكن تركها فارغة أو إعداد مهام خفيفة (غير async) }
@override Future onDestroy(DateTime timestamp, bool isOnMainThread) async { // تنظيف الموارد إذا لزم الأمر }
String formatBytes(String bytes) { try { final value = int.parse(bytes); if (value < 1024) return '{(value / 1024).toStringAsFixed(1)} كيلوبايت'; if (value < 1024 * 1024 * 1024) return '{(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت'; } catch () { return bytes; } } }
- Assistant
بالطبع، سأصحح لك الكود وأشير إلى أبرز المشاكل التي وجدتُها مع التعديلات اللازمة لتشغيل خدمة الـ foreground بشكل صحيح وضمان بناء واجهة التطبيق بسلاسة.
1. أخطاء ومشاكل رئيسية في كودك:
- في ملف
main()وخاصة تعريفForegroundTaskOptions، لا تستخدمeventAction! (غير موجود حاليًا في الإصدار) ولكن استخدمeventIntervalبشكل صحيح. - في
WithForegroundTaskيجب تمرير نفس خيارات الإشعارات وخدمةforegroundTaskOptionsكما هي في تهيئة المكتبة. - هناك خطأ في استخدام
Icons.mp_rounded(غير موجود) في العرض بعنوان IP؛ استبدلها بـIcons.ip_rounded. - في بعض الأماكن، طريقة التحديث أو نداء دوال اللانك بعد بداية الـforeground service خطأ أو يحتاج تعديل.
- يجب استعمال
awaitفي بعض النجاحات التي تتعلق بتشغيل وإيقاف الخدمة لتأكيد التنفيذ الصحيح.
2. الكود المصحح بالكامل:
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:http/http.dart' as http; void main() async { WidgetsFlutterBinding.ensureInitialized(); await FlutterForegroundTask.init( androidNotificationOptions: const AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationChannelImportance.DEFAULT, priority: NotificationPriority.DEFAULT, iconData: NotificationIconData( resType: ResourceType.mipmap, resPrefix: ResourcePrefix.ic, name: 'launcher', ), ), iosNotificationOptions: const IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: const ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, eventInterval: 5000, // 5 ثواني ), ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Network Monitor', theme: ThemeData( primarySwatch: Colors.blue, fontFamily: 'Tajawal', scaffoldBackgroundColor: const Color(0xFFF5F7FA), ), home: const LoginScreen(), debugShowCheckedModeBanner: false, ); } } class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); @override State<LoginScreen> createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { final _formKey = GlobalKey<FormState>(); final _usernameController = TextEditingController(); final _passwordController = TextEditingController(); bool _isLoggingIn = false; bool _obscurePassword = true; @override void dispose() { _usernameController.dispose(); _passwordController.dispose(); super.dispose(); } Future<void> _login() async { if (!_formKey.currentState!.validate()) return; setState(() => _isLoggingIn = true); try { final response = await http .post( Uri.parse('http://172.16.0.1/login'), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: { 'username': _usernameController.text, 'password': _passwordController.text, }, ) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { final data = json.decode(response.body); if (data['status'] == 'success' && mounted) { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => DashboardScreen( username: _usernameController.text, userData: { 'username': _usernameController.text, 'ip': data['ip'] ?? 'غير معروف', 'mac': data['mac'] ?? 'غير معروف', }, ), ), ); } else { throw Exception(data['message'] ?? 'فشل تسجيل الدخول'); } } else { throw Exception('فشل الاتصال بالخادم'); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('حدث خطأ: ${e.toString()}'), backgroundColor: Colors.red, behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } } finally { if (mounted) setState(() => _isLoggingIn = false); } } @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.rtl, child: Scaffold( body: SafeArea( child: SingleChildScrollView( padding: const EdgeInsets.all(24.0), child: Column( children: [ const SizedBox(height: 40), Image.asset( 'assets/network_icon.png', height: 120, width: 120, ), const SizedBox(height: 32), Text( 'مرحباً بعودتك', style: Theme.of(context).textTheme.headlineSmall?.copyWith( fontWeight: FontWeight.bold, color: const Color(0xFF2E384D), ), ), const SizedBox(height: 8), Text( 'سجل الدخول للوصول إلى حسابك', style: Theme.of(context).textTheme.bodyMedium?.copyWith( color: const Color(0xFF8798AD), ), ), const SizedBox(height: 32), Form( key: _formKey, child: Column( children: [ TextFormField( controller: _usernameController, decoration: InputDecoration( labelText: 'اسم المستخدم', prefixIcon: const Icon( Icons.person_outline_rounded, color: Color(0xFFB0BAC9), ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Color(0xFFE0E6ED)), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Color(0xFFE0E6ED)), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.isEmpty) { return 'الرجاء إدخال اسم المستخدم'; } return null; }, ), const SizedBox(height: 16), TextFormField( controller: _passwordController, obscureText: _obscurePassword, decoration: InputDecoration( labelText: 'كلمة المرور', prefixIcon: const Icon( Icons.lock_outline_rounded, color: Color(0xFFB0BAC9), ), suffixIcon: IconButton( icon: Icon( _obscurePassword ? Icons.visibility_off_outlined : Icons.visibility_outlined, color: const Color(0xFFB0BAC9), ), onPressed: () { setState(() { _obscurePassword = !_obscurePassword; }); }, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Color(0xFFE0E6ED)), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Color(0xFFE0E6ED)), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.isEmpty) { return 'الرجاء إدخال كلمة المرور'; } return null; }, ), const SizedBox(height: 24), SizedBox( width: double.infinity, height: 50, child: ElevatedButton( onPressed: _isLoggingIn ? null : _login, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF3366FF), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), elevation: 0, shadowColor: Colors.transparent, ), child: _isLoggingIn ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Text( 'تسجيل الدخول', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ], ), ), ), ), ); } } class DashboardScreen extends StatefulWidget { final String username; final Map<String, dynamic> userData; const DashboardScreen({ super.key, required this.username, required this.userData, }); @override State<DashboardScreen> createState() => _DashboardScreenState(); } class _DashboardScreenState extends State<DashboardScreen> with WidgetsBindingObserver { bool _isLoggingOut = false; Timer? _timer; late Map<String, dynamic> _currentUserData; bool _isForegroundServiceRunning = false; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _currentUserData = Map<String, dynamic>.from(widget.userData); _startPeriodicUpdate(); } @override void dispose() { _timer?.cancel(); WidgetsBinding.instance.removeObserver(this); _stopForegroundService(); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (!mounted) return; if (state == AppLifecycleState.paused) { _startForegroundService(); } else if (state == AppLifecycleState.resumed) { _stopForegroundService(); } } Future<void> _startForegroundService() async { if (_isForegroundServiceRunning) return; await FlutterForegroundTask.startService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'جاري تحديث البيانات...', callback: startCallback, ); if (mounted) setState(() => _isForegroundServiceRunning = true); } Future<void> _stopForegroundService() async { await FlutterForegroundTask.stopService(); if (mounted) setState(() => _isForegroundServiceRunning = false); } void _startPeriodicUpdate() { _timer = Timer.periodic(const Duration(seconds: 5), (_) async { await _updateUserData(); }); } Future<void> _updateUserData() async { try { final response = await http .get(Uri.parse('http://172.16.0.1/status?var=json')) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { final data = json.decode(response.body); if (data.containsKey('errors')) return; if (!mounted) return; setState(() { _currentUserData = { 'logged_in': data['logged_in'] ?? 'no', 'username': data['username'] ?? widget.username, 'mac': _decodeMacAddress(data['mac'] ?? ''), 'ip': data['ip'] ?? 'غير معروف', 'bytes_in': _formatBytes(data['bytes_in'] ?? '0'), 'bytes_out': _formatBytes(data['bytes_out'] ?? '0'), 'remain_bytes_total': _formatBytes(data['remain_bytes_total'] ?? '0'), 'uptime': _formatUptimeExtended(data['uptime'] ?? '0s'), 'session_time_left': _formatSessionTimeLeft(data['session_time_left'] ?? 'غير محدود'), }; }); if (_isForegroundServiceRunning) { FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'IP: ${_currentUserData['ip']} | المستلم: ${_currentUserData['bytes_in']} | المرسل: ${_currentUserData['bytes_out']} | المتبقي: ${_currentUserData['session_time_left']}', ); } } } catch (_) { if (_isForegroundServiceRunning) { FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'خطأ في تحديث البيانات', ); } } } Future<void> _logout() async { setState(() => _isLoggingOut = true); try { await _stopForegroundService(); final response = await http .post( Uri.parse('http://172.16.0.1/logout'), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: {'username': widget.username}, ) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { if (mounted) { Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (_) => const LoginScreen()), (route) => false, ); } } else { throw Exception('فشل في تسجيل الخروج'); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('حدث خطأ: ${e.toString()}'), backgroundColor: Colors.red, behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } } finally { if (mounted) { setState(() => _isLoggingOut = false); } } } String _decodeMacAddress(String encodedMac) { return encodedMac.replaceAll('%3A', ':'); } String _formatBytes(String bytes) { try { final value = int.parse(bytes); if (value < 1024) return '$value بايت'; if (value < 1024 * 1024) return '${(value / 1024).toStringAsFixed(1)} كيلوبايت'; if (value < 1024 * 1024 * 1024) return '${(value / (1024 * 1024)).toStringAsFixed(1)} ميجابايت'; return '${(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت'; } catch (_) { return bytes; } } String _formatUptimeExtended(String uptime) { final regex = RegExp(r'(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?'); final match = regex.firstMatch(uptime); if (match == null) return uptime; final days = int.tryParse(match.group(1) ?? '0') ?? 0; final hours = int.tryParse(match.group(2) ?? '0') ?? 0; final minutes = int.tryParse(match.group(3) ?? '0') ?? 0; final seconds = int.tryParse(match.group(4) ?? '0') ?? 0; String result = ''; if (days > 0) result += '$days يوم '; if (hours > 0) result += '$hours ساعة '; if (minutes > 0) result += '$minutes دقيقة '; if (seconds > 0) result += '$seconds ثانية'; return result.trim(); } String _formatSessionTimeLeft(String sessionTimeLeft) { if (sessionTimeLeft == 'غير محدود') return sessionTimeLeft; return _formatUptimeExtended(sessionTimeLeft); } @override Widget build(BuildContext context) { return WithForegroundTask( androidNotificationOptions: const AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationChannelImportance.DEFAULT, priority: NotificationPriority.DEFAULT, iconData: NotificationIconData( resType: ResourceType.mipmap, resPrefix: ResourcePrefix.ic, name: 'launcher', ), ), iosNotificationOptions: const IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: const ForegroundTaskOptions( allowWakeLock: true, allowWifiLock: true, autoRunOnBoot: false, eventInterval: 5000, ), child: Directionality( textDirection: TextDirection.rtl, child: Scaffold( backgroundColor: const Color(0xFFF5F7FA), appBar: AppBar( title: const Text('لوحة التحكم'), centerTitle: true, elevation: 0, backgroundColor: Colors.transparent, foregroundColor: const Color(0xFF2E384D), automaticallyImplyLeading: false, actions: [ IconButton( icon: const Icon(Icons.refresh_rounded), onPressed: _updateUserData, tooltip: 'تحديث البيانات', ), ], ), body: SafeArea( child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ _buildModernUserCard(context), const SizedBox(height: 24), Expanded( child: GridView.count( crossAxisCount: 2, childAspectRatio: 1.1, crossAxisSpacing: 16, mainAxisSpacing: 16, children: [ _buildModernStatCard( icon: Icons.timer_rounded, title: 'مدة الاتصال', value: _currentUserData['uptime'] ?? 'غير معروف', color: const Color(0xFF3366FF), ), _buildModernStatCard( icon: Icons.download_rounded, title: 'البيانات المستلمة', value: _currentUserData['bytes_in'] ?? '0', color: const Color(0xFF00C1D4), ), _buildModernStatCard( icon: Icons.upload_rounded, title: 'البيانات المرسلة', value: _currentUserData['bytes_out'] ?? '0', color: const Color(0xFFFF8A34), ), _buildModernStatCard( icon: Icons.access_time_filled_rounded, title: 'الوقت المتبقي', value: _currentUserData['session_time_left'] ?? 'غير محدود', color: const Color(0xFF50B83C), ), _buildModernStatCard( icon: Icons.data_usage_rounded, title: 'البيانات المتبقية', value: _currentUserData['remain_bytes_total'] ?? '0', color: const Color(0xFF9C6ADE), ), _buildModernStatCard( icon: Icons.network_check_rounded, title: 'حالة الاتصال', value: 'نشط', color: const Color(0xFFF7C948), ), ], ), ), const SizedBox(height: 16), SizedBox( width: double.infinity, child: ElevatedButton.icon( onPressed: _isLoggingOut ? null : _logout, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFFFF453A), foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(vertical: 16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), elevation: 0, ), icon: _isLoggingOut ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Icon(Icons.logout_rounded, size: 20), label: Text( _isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج', style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ), ), ), ); } Widget _buildModernUserCard(BuildContext context) { return Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), color: Colors.white, boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.1), blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ Row( children: [ Container( width: 60, height: 60, decoration: BoxDecoration( color: const Color(0xFF3366FF).withOpacity(0.1), shape: BoxShape.circle, ), child: const Icon( Icons.person_rounded, size: 30, color: Color(0xFF3366FF), ), ), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _currentUserData['username'] ?? widget.username, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, fontFamily: 'Tajawal', color: Color(0xFF2E384D), ), maxLines: 1, overflow: TextOverflow.ellipsis, ), const SizedBox(height: 4), const Text( 'مستخدم Hotspot', style: TextStyle( fontSize: 14, color: Color(0xFF8798AD), fontFamily: 'Tajawal', ), ), ], ), ), ], ), const SizedBox(height: 16), Divider(color: Colors.grey.withOpacity(0.2), height: 1), const SizedBox(height: 12), _buildModernInfoRow( Icons.ip_rounded, 'عنوان IP:', _currentUserData['ip'] ?? 'غير معروف', const Color(0xFF2E384D), ), _buildModernInfoRow( Icons.device_hub_rounded, 'عنوان MAC:', _currentUserData['mac'] ?? 'غير معروف', const Color(0xFF2E384D), ), ], ), ), ); } Widget _buildModernInfoRow( IconData icon, String label, String value, Color color, ) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: Row( children: [ Icon(icon, size: 20, color: color.withOpacity(0.6)), const SizedBox(width: 12), Text( label, style: TextStyle( fontWeight: FontWeight.bold, fontFamily: 'Tajawal', fontSize: 15, color: color.withOpacity(0.8), ), ), const SizedBox(width: 8), Expanded( child: Text( value, style: TextStyle( color: color, overflow: TextOverflow.ellipsis, fontFamily: 'Tajawal', ), ), ), ], ), ); } Widget _buildModernStatCard({ required IconData icon, required String title, required String value, required Color color, }) { return Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(16), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.1), blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Padding( padding: const EdgeInsets.all(16), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: color.withOpacity(0.1), borderRadius: BorderRadius.circular(12), ), child: Icon(icon, size: 24, color: color), ), const SizedBox(height: 12), Text( value, style: const TextStyle( fontFamily: 'Tajawal', fontSize: 16, fontWeight: FontWeight.bold, color: Color(0xFF2E384D), ), ), const SizedBox(height: 4), Text( title, style: const TextStyle( fontFamily: 'Tajawal', fontSize: 13, color: Color(0xFF8798AD), ), ), ], ), ), ); } } // بدء خدمة الـ foreground task @pragma('vm:entry-point') void startCallback() { FlutterForegroundTask.setTaskHandler(NetworkStatusTaskHandler()); } class NetworkStatusTaskHandler extends TaskHandler { @override Future<void> onStart(DateTime timestamp, TaskStarter taskStarter) async { // يمكن إضافة إعدادات أولية عند بدء المهمة } @override Future<void> onEvent(DateTime timestamp) async { try { final response = await http .get(Uri.parse('http://172.16.0.1/status?var=json')) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { final data = json.decode(response.body); if (data.containsKey('errors')) return; final username = data['username'] ?? 'غير معروف'; final ip = data['ip'] ?? 'غير معروف'; final bytesIn = _formatBytes(data['bytes_in'] ?? '0'); final bytesOut = _formatBytes(data['bytes_out'] ?? '0'); final sessionTimeLeft = data['session_time_left'] ?? 'غير محدود'; await FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - $username', notificationText: 'IP: $ip | المستلم: $bytesIn | المرسل: $bytesOut | المتبقي: $sessionTimeLeft', ); } } catch (_) { await FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة', notificationText: 'خطأ في تحديث البيانات', ); } } @override void onRepeatEvent(DateTime timestamp) { // يمكن تركها فارغة أو إضافة مهام غير متزامنة } @override Future<void> onDestroy(DateTime timestamp, bool isOnMainThread) async { // تنظيف الموارد عند إنهاء المهمة, إذا لزم الأمر } static String _formatBytes(String bytes) { try { final value = int.parse(bytes); if (value < 1024) return '$value بايت'; if (value < 1024 * 1024) return '${(value / 1024).toStringAsFixed(1)} كيلوبايت'; if (value < 1024 * 1024 * 1024) return '${(value / (1024 * 1024)).toStringAsFixed(1)} ميجابايت'; return '${(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت'; } catch (_) { return bytes; } } }
3. ملاحظات وأفضل ممارسات:
- مراجعة الملف
android/app/src/main/AndroidManifest.xmlوإضافة الصلاحيات التالية لتشغيل الخدمة في الخلفية ضمن<manifest>:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.WAKE_LOCK" />- تحديث
pubspec.yaml: تأكد من إضافة صورة الأيقونة والمسار الصحيح وكذلك العائلة الخطية "Tajawal" إذا استخدمتها. - ينصح بعدم تقليل فترة التحديث إلى أقل من 5 ثواني لتوفير البطارية والحفاظ على الأداء.
- اختبار التطبيق على جهاز حقيقي مع إعطاء الأذونات يدوياً أو عبر الأكواد.
إذا طبقت هذه التعديلات والكود أعلاه، يجب أن يعمل التطبيق مع تشغيل خدمة foreground بشكل سليم مع تحديث الإشعارات في الخلفية.
إذا واجهت أي مشاكل أخرى أو أخطاء عند التنفيذ، أرجو إعلامي لأساعدك في حلها!
- في ملف
- User
اريد اسلوب يتوافق مع اصدار flutter_foreground_task: ^9.1.0 للعلم الاخطاء await FlutterForegroundTask.init( androidNotificationOptions: const AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationChannelImportance.DEFAULT, priority: NotificationPriority.DEFAULT, iconData: NotificationIconData( resType: ResourceType.mipmap, resPrefix: ResourcePrefix.ic, name: 'launcher', ), ), iosNotificationOptions: const IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: const ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, eventInterval: 5000, // 5 ثواني ), );
runApp(const MyApp()); } و androidNotificationOptions: const AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationChannelImportance.DEFAULT, priority: NotificationPriority.DEFAULT, iconData: NotificationIconData( resType: ResourceType.mipmap, resPrefix: ResourcePrefix.ic, name: 'launcher', ), ), iosNotificationOptions: const IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: const ForegroundTaskOptions( allowWakeLock: true, allowWifiLock: true, autoRunOnBoot: false, eventInterval: 5000, ),
- Assistant
شكرًا لتوضيح إصدار مكتبة
flutter_foreground_taskالذي تستخدمه (الإصدار 9.1.0). هذا الإصدار يحتوي على تغييرات في API الخاصة بالتهيئة والاستخدام مقارنةً بالإصدارات الأحدث.
مشاكل رئيسية في الكود لنسخة 9.1.0:
- في الإصدار 9.1.0، دالة
FlutterForegroundTask.initغير متوافقة مع الاستدعاءات التي تحتوي علىiconData،channelImportanceوpriorityفيAndroidNotificationOptionsكما في الإصدارات الجديدة. - كذلك، لا يوجد حقل
eventIntervalفيForegroundTaskOptions، ولكن هناكinterval. - يجب عدم استخدام
constمع كائناتAndroidNotificationOptionsوForegroundTaskOptionsفي هذا الإصدار. - طريقة نقل خصائص
androidNotificationOptions،iosNotificationOptions، وforegroundTaskOptionsعند استخدام ويدجتWithForegroundTaskتختلف قليلاً أو تحتاج تعيينها كـ final properties وليستconst.
الحل المناسب لإصدار
flutter_foreground_task: ^9.1.01. تهيئة الخدمة في
main:void main() async { WidgetsFlutterBinding.ensureInitialized(); await FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, interval: 5000, ), ); runApp(const MyApp()); }ملحوظات:
- لا تستخدم
NotificationChannelImportanceوNotificationPriorityبل استخدمNotificationImportanceفقط. - لا تستخدم
iconDataهنا فيAndroidNotificationOptions(كانت موجودة بالإصدارات الأعلى فقط). intervalبالقيم بالميلي ثانية (هنا 5000 تعني 5 ثواني).
2. عند استخدام
WithForegroundTask:return WithForegroundTask( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( allowWakeLock: true, allowWifiLock: true, autoRunOnBoot: false, interval: 5000, ), child: Directionality( textDirection: TextDirection.rtl, child: ..., ), );
3. مثال كامل مختصر للتهيئة مع الإصدار 9.1.0:
import 'package:flutter/material.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, interval: 5000, ), ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return WithForegroundTask( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( allowWakeLock: true, allowWifiLock: true, autoRunOnBoot: false, interval: 5000, ), child: MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('مثال خدمة أمامية')), body: Center( child: ElevatedButton( child: const Text('تشغيل الخدمة'), onPressed: () async { await FlutterForegroundTask.startService( notificationTitle: 'الخدمة تعمل', notificationText: 'هذه خدمة أمامية تعمل في الخلفية', callback: startCallback, ); }, ), ), ), ), ); } } @pragma('vm:entry-point') void startCallback() { FlutterForegroundTask.setTaskHandler(MyTaskHandler()); } class MyTaskHandler extends TaskHandler { @override Future<void> onStart(DateTime timestamp, TaskStarter taskStarter) async {} @override Future<void> onEvent(DateTime timestamp) async { // حدث دوري كل 5 ثواني await FlutterForegroundTask.updateService( notificationTitle: 'الخدمة تعمل', notificationText: 'التحديث عند ${DateTime.now()}', ); } @override void onRepeatEvent(DateTime timestamp) {} @override Future<void> onDestroy(DateTime timestamp, bool isOnMainThread) async {} }
ملخص التعديلات:
خاصية/كائن النسخة 9.1.0 نسخة أحدث (مثلاً 10+) androidNotificationOptionsNotificationImportanceفقط (بدونNotificationChannelImportanceأوNotificationPriority)NotificationChannelImportanceوNotificationPriorityمتاحةiconDataغير مدعومة في init() مدعومة وأكثر تفصيلاً foregroundTaskOptionsتستخدم الحقل intervalبالميلي ثانيةتستخدم eventIntervalمع Durationالإعلانات const لا تستخدم const في التهيئة متاحة مع const
روابط مفيدة:
- صفحة حزمة flutter_foreground_task على pub.dev
- مثال رسمي قديم على GitHub يتوافق مع هذا الإصدار يمكن أخذ منه الملاحظات.
إذا احتجت دعمًا في تعديل أي جزء من تطبيقك ليعمل متوافقًا مع نسخة 9.1.0، يمكنك إرسال الكود الذي يعمل به الخطأ وسأساعدك بتعديله.
- في الإصدار 9.1.0، دالة
- User
كم اضع الاصدار هنا flutter_foreground_task:
- Assistant
للحصول على إصدار 9.1.0 من مكتبة
flutter_foreground_task، يمكنك تحديده في ملفpubspec.yamlبهذا الشكل:dependencies: flutter_foreground_task: ^9.1.0هذا يطلب نسخة 9.1.0 أو أي نسخة تحديث فرعي (patch) ضمن 9.1.x، ولن يظهر إصدار أعلى مثل 10.0.0 وما فوق.
مثال كامل:
dependencies: flutter: sdk: flutter flutter_foreground_task: ^9.1.0بعد حفظ الملف، شغّل الأمر:
flutter pub getلتثبيت النسخة المحددة في مشروعك.
إذا كنت تريد حقيبة
flutter_foreground_taskبرقم إصدار ثابت (تحديد دقيق جدًا للنسخة بدون تحديثات فرعية) يمكنك حذف علامة^:flutter_foreground_task: 9.1.0لكن عادةً يفضل استخدام الأمر مع
^لالتقاط التحديثات الأمنية أو الإصلاحات الطفيفة. - User
اريد اصدار يتوافق مع هذا await FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, interval: 5000, ), );
- Assistant
الكود الذي تستخدمه مع:
await FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, interval: 5000, ), );هو مطابق تمامًا لنسخة
flutter_foreground_task9.0.0 إلى 9.3.0 (أي ضمن إصدار 9.x.x).
بالتالي، يمكنك تحديد هذا الإصدار أو أي إصدار ضمن سلسلة 9 مثل:
dependencies: flutter_foreground_task: ^9.3.0وهذا سيستخدم إصدارًا متوافقًا مع الكود.
إذا تريد تثبيت إصدار معين محدد (مثلاً 9.1.0):
dependencies: flutter_foreground_task: 9.1.0
ملخص:
كود التهيئة إصدار المكتبة المتوافق NotificationImportance+interval+AndroidNotificationOptionsبدونchannelImportanceمن نوع NotificationChannelImportance (أي النوع القديم)9.x.x(مثلاً9.1.0أو9.3.0)
ملاحظات:
- في إصدارات
10.xوأعلى تم تغيير واجهة برمجة التطبيقات (API) واختلف الكود لذا لا يمكن تشغيل هذا الكود بالشكل السابق علىflutter_foreground_taskإصدارات عالية جدًا. - لتجنب مشاكل، ينصح بإضافة هذا السطر مع نسخة 9 فقط في pubspec.yaml ثم تشغيل:
flutter pub get
لو تحتاج مثال عملي كامل مع هذا الإصدار، سأوفره لك. فقط أخبرني!
- في إصدارات
- User
اريد ملف ال runner service .kt لحل المشاكل
await FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, interval: 5000, ), );
runApp(const MyApp()); } وهنا return WithForegroundTask( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( allowWakeLock: true, allowWifiLock: true, autoRunOnBoot: false, interval: 5000, ),
- Assistant
بالتأكيد، سأوفر لك ملف Runner Service (ForegroundService.kt) الذي تحتاجه لتشغيل الخدمة الأمامية (Foreground Service) مع مكتبة
flutter_foreground_taskمع الإعدادات التي وضعتها.
1. أين تضع الملف؟
يمكنك إنشاء ملف ForegroundService.kt أو RunnerService.kt داخل مجلد:
android/app/src/main/kotlin/your/package/name/حيث
your.package.nameهو باكدج التطبيق (مثلاً: com.example.app).
2. محتوى ملف RunnerService.kt المتوافق (مثال):
package your.package.name import android.app.Notification import android.app.PendingIntent import android.content.Intent import android.os.Build import android.os.IBinder import android.app.Service import androidx.core.app.NotificationCompat import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.dart.DartExecutor import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.PluginRegistry class RunnerService : Service() { private val CHANNEL_ID = "network_monitor_channel" private val NOTIFICATION_ID = 8080 override fun onCreate() { super.onCreate() startForeground(NOTIFICATION_ID, createNotification()) } private fun createNotification(): Notification { val notificationIntent = Intent(this, MainActivity::class.java) notificationIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val pendingIntent = PendingIntent.getActivity( this, 0, notificationIntent, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else PendingIntent.FLAG_UPDATE_CURRENT ) return NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Network Monitor") .setContentText("جاري تحديث البيانات...") .setSmallIcon(R.mipmap.ic_launcher) // تأكد من وجود الأيقونة هنا .setContentIntent(pendingIntent) .setOngoing(true) .build() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { // إذا أردت تنفيذ شيء أثناء بدء الخدمة، كمزامنة إضافية مع النظام return START_STICKY } override fun onBind(intent: Intent?): IBinder? { // لا داعي للربط عند عدم الحاجة return null } override fun onDestroy() { stopForeground(true) super.onDestroy() } }
3. تحديث AndroidManifest.xml
داخل ملف
android/app/src/main/AndroidManifest.xmlقم بإضافة الخدمة داخل<application>:<service android:name=".RunnerService" android:enabled="true" android:exported="false" android:foregroundServiceType="location|dataSync" />يمكنك استبدال
android:foregroundServiceTypeبأنواع الخدمة التي تناسب تطبيقك، مثلاً:dataSynclocationmediaPlaybackphoneCall
وغيرها حسب طبيعة الخدمة.
إذا لم تكن متأكدًا ابدأ بـdataSyncأوnone.
4. ملاحظات مهمة
- تأكد من أن اسم الباكيج في أعلى الملف Kotlin (
package your.package.name) مطابق تمامًا لمسار مشروعك. - تأكد من وجود أيقونة التطبيق في مجلد
mipmapبالاسمic_launcher.pngأو غيره حسب ما استخدمته. - في بعض حالات استخدام المكتبة لا تحتاج لإنشاء ملف الخدمة يدويا إذا كانت المكتبة الخاصة بك تستدعي الخدمة الخاصة بها. لكن إنشاء ملف الخدمة المخصصة يعطيك تحكمًا أكبر.
flutter_foreground_taskعموما تدير تشغيل الخدمة تلقائياً، لكن في بعض الحالات المتقدمة أو تخصيص الإشعارات تحتاج ملف مثل هذا.
5. توثيق مكتبة
flutter_foreground_taskمكتبة
flutter_foreground_taskتوفر خدمة جاهزة وتديرها تلقائياً، لذلك في معظم الحالات لا تحتاج هذا الملف إلا إذا كنت تريد تخصيص طريقة عرض الإشعار أو سلوك الخدمة. هناك إعداد ضمن المكتبة يمكن تخصيص الإشعارات بسهولة من خلالAndroidNotificationOptions.إذا كنت تواجه مشاكل محددة تُظهر ملفات خدمة غير موجودة أو الأذونات مفقودة، تأكد من:
- وجود أذونات في
AndroidManifest.xml:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.WAKE_LOCK" />- تحديث إعدادات
AndroidNotificationOptionsفي تهيئة الخدمة كما هو موضح سابقا بهيئة متوافقة مع إصدار المكتبة.
ملخص:
- جرّب أولًا تهيئة المكتبة بدون إنشاء خدمة خاصة
RunnerService.kt، لأن مكتبةflutter_foreground_taskتدير ذلك بنفسها. - لإنشاء خدمة مخصصة، استخدم الكود السابق مع المسار الصحيح في مشروعك.
- أضف الخدمة إلى المانيفست.
- تأكد من وجود صلاحيات الخدمة الأمامية في المانيفست.
إذا تريد كود مخصص لتخصيص الخدمة مع تفاعل أكبر مع نظام Flutter، أخبرني لأرفقه لك.
- User
تقصد هذا الملف package com.example.hotspot
import io.flutter.embedding.android.FlutterActivity import com.pravera.flutter_foreground_task.FlutterForegroundTaskPlugin
class MainActivity : FlutterActivity()
- Assistant
الكود الذي أرسلته هو كود Activity رئيسي بسيط لتطبيق Flutter وهو ليس ملف "Runner Service" (أو Foreground Service) الذي يتم استخدامه لتشغيل خدمة foreground (الخدمة الأمامية) في أندرويد.
توضيح الفرق:
MainActivity.kt(أو MainActivity.java) هو النشاط (Activity) الأساسي الذي يبدأ التطبيق وهو مسؤول عن عرض واجهة المستخدم.- Runner Service (Foreground Service) هو خدمة (Service) تعمل في الخلفية مع إشعار دائم، وتستخدم بشكل خاص عند استدعاء
flutter_foreground_taskلتشغيل المهام في الخلفية عندما يكون التطبيق في الخلفية أو مغلقًا.
هل تحتاج ملف Service (كما طلبت)؟
-
مع مكتبة
flutter_foreground_taskوالإصدار 9.1.0 أو قريب منه عادةً لا تحتاج إلى كتابة ملف خدمة.ktبنفسك.
لأن المكتبة تأتي مع خدمة foreground مدارة داخلياً تعمل تلقائياً. -
لكن إذا واجهت مشاكل أو أردت تخصيص الخدمة الأمامية (مثلاً تخصيص الإشعارات أو سلوك الخدمة)، حينها تكتب ملف خدمة Kotlin منفصل مثل المثال الذي أعطيتك سابقًا (RunnerService.kt).
ماذا تفعل في ملف
MainActivity.ktمع المكتبة؟عادةً ملف
MainActivity.ktيبقى بسيطًا مثل:package com.example.hotspot import io.flutter.embedding.android.FlutterActivity class MainActivity : FlutterActivity()أو (حسب توجيهات المكتبة وأندرويد):
package com.example.hotspot import io.flutter.embedding.android.FlutterActivity import com.pravera.flutter_foreground_task.FlutterForegroundTaskPlugin class MainActivity : FlutterActivity() { // غالبًا لا تحتاج إضافة شيء، الإضافة السابقة كانت قديمة أو لدعم Legacy embedding. }
خطوات مهمة إضافية:
- تأكد أنك أضفت الصلاحيات في
AndroidManifest.xml:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.WAKE_LOCK" />- خدمة foreground في المانيفست (إذا كنت تكتب خدمة مخصصة):
<service android:name=".RunnerService" android:enabled="true" android:exported="false" android:foregroundServiceType="dataSync" />- في أغلب الحالات، لا تضيف خدمة مخصصة، و
flutter_foreground_taskتدير الخدمة تلقائيًا عند استدعاء:
await FlutterForegroundTask.startService( notificationTitle: '...', notificationText: '...', callback: startCallback, );
خلاصة:
- ملف
MainActivity.ktبسيط لا علاقة له بالخدمة الأمامية. - الخدمة الأمامية تكون ملف Kotlin مستقل (RunnerService.kt) فقط إذا أردت تخصيص الخدمة.
- المكتبة تدير جميع الخدمات التأهيلية في الخلفية بشكل تلقائي.
- تأكد من إعدادات الإشعارات في
AndroidNotificationOptionsوصلاحيات الخدمة الأمامية.
إذا تريد، أرسل لي مشكلة أو خطأ إحدى منها تظهرها في التطبيق عند تشغيل الخدمة الأمامية، لأساعدك خطوة بخطوة مع الحل.
- User
قمت بانشاء ملف RunnerService.kt ماذا اقوم بوضع داخلة
- Assistant
إذا أنشأت ملف
RunnerService.ktفي مشروع Flutter الخاص بك لاستخدامه مع مكتبةflutter_foreground_task(الإصدار 9.x)، وتريد خدمة foreground مخصصة (Notification و Service خاصة)، فأفضل محتوى يمكنك وضعه فيه هو كود Kotlin بسيط لإنشاء خدمة foreground مع إشعار ثابت.
ملف RunnerService.kt نموذجي يتوافق مع
flutter_foreground_taskنسخة 9.xpackage com.example.hotspot // عدل هذا إلى باكدج مشروعك import android.app.Notification import android.app.PendingIntent import android.content.Intent import android.os.Build import android.os.IBinder import androidx.core.app.NotificationCompat import android.app.Service class RunnerService : Service() { companion object { const val CHANNEL_ID = "network_monitor_channel" const val NOTIFICATION_ID = 1 } override fun onCreate() { super.onCreate() startForeground(NOTIFICATION_ID, buildNotification()) } private fun buildNotification(): Notification { val notificationIntent = Intent(this, MainActivity::class.java) notificationIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP val pendingIntentFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else PendingIntent.FLAG_UPDATE_CURRENT val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, pendingIntentFlag) return NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Network Monitor") .setContentText("تعمل خدمة الشبكة في الخلفية") .setSmallIcon(R.mipmap.ic_launcher) // تأكد من وجود الأيقونة هنا .setContentIntent(pendingIntent) .setOngoing(true) .build() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { // يمكنك تنفيذ تعليمات عند بدء الخدمة (مثلاً تهيئة إضافية) return START_STICKY } override fun onBind(intent: Intent?): IBinder? { // لا داعي للربط مع هذا النوع من الخدمات return null } override fun onDestroy() { super.onDestroy() stopForeground(true) } }
نقاط مهمة:
- غيّر
package com.example.hotspotليطابق باكدج مشروعك (كما هو معرف في ملفAndroidManifest.xml). - تأكد من وجود الأيقونة
ic_launcherفي مجلدres/mipmap. - في ملف
AndroidManifest.xmlأضف الخدمة تحت الوسم<application>:
<service android:name=".RunnerService" android:enabled="true" android:exported="false" android:foregroundServiceType="dataSync" />يمكنك تغيير
android:foregroundServiceTypeحسب طبيعة الخدمة (مثلاًdataSync,location,mediaPlayback,...)، أو حذفه إذا تريد التصريح الافتراضي.- الصلاحيات المطلوبة يجب إضافتها في المانيفست كذلك:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
استخدام مكتبة flutter_foreground_task مع هذه الخدمة
إذا أردت ربط هذه الخدمة مع
flutter_foreground_task، عادة يبدأ تشغيل الخدمة تلقائيًا من:await FlutterForegroundTask.startService( notificationTitle: 'Network Monitor', notificationText: 'تعمل خدمة الشبكة في الخلفية', callback: startCallback, );ولكن إذا أردت أن تستخدم خدمتك اليدوية RunnerService.kt، ستحتاج لتعديل واجهة Flutter API للتعامل مع هذا ولا ينصح بذلك إلا عند الحاجة لتخصيصات كبيرة.
خلاصة
- هذا الكود يجعل لديك foreground service بسيط ظاهر كإشعار في شريط الهاتف.
- توصيله مع مكتبة
flutter_foreground_taskيتم غالبًا تلقائيًا بدون الحاجة لكتابة خدمة مخصصة. - أنشئ الملف وضع هذا الكود وعدّل المسارات واسم الباكيج.
- اضف الملف في
AndroidManifest.xml. - أعطِ الأذونات المطلوبة.
- شغّل الخدمة من Flutter باستخدام
FlutterForegroundTask.startService().
إذا تحتاج كود تفعيل أو مثال كامل أو شرح داخلي أكثر عن كيفية الربط مع المكتبة، أخبرني.
- غيّر
- User
بعد انشاء الملف لماذا ماتزال هناك اخطاء هنا return WithForegroundTask( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( allowWakeLock: true, allowWifiLock: true, autoRunOnBoot: false, interval: 5000, ), وهنا await FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, interval: 5000, ), ); الكود الكالي import 'dart:async'; import 'dart:convert';
import 'package:flutter/material.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:http/http.dart' as http;
void main() async { WidgetsFlutterBinding.ensureInitialized();
await FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, interval: 5000, ), );
runApp(const MyApp()); }
class MyApp extends StatelessWidget { const MyApp({super.key});
@override Widget build(BuildContext context) { return MaterialApp( title: 'Network Monitor', theme: ThemeData( primarySwatch: Colors.blue, fontFamily: 'Tajawal', scaffoldBackgroundColor: const Color(0xFFF5F7FA), ), home: const LoginScreen(), debugShowCheckedModeBanner: false, ); } }
class LoginScreen extends StatefulWidget { const LoginScreen({super.key});
@override State createState() => _LoginScreenState(); }
class _LoginScreenState extends State { final _formKey = GlobalKey(); final _usernameController = TextEditingController(); final _passwordController = TextEditingController(); bool _isLoggingIn = false; bool _obscurePassword = true;
@override void dispose() { _usernameController.dispose(); _passwordController.dispose(); super.dispose(); }
Future _login() async { if (!_formKey.currentState!.validate()) return;
setState(() => _isLoggingIn = true); try { final response = await http .post( Uri.parse('http://172.16.0.1/login'), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: { 'username': _usernameController.text, 'password': _passwordController.text, }, ) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { final data = json.decode(response.body); if (data['status'] == 'success' && mounted) { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => DashboardScreen( username: _usernameController.text, userData: { 'username': _usernameController.text, 'ip': data['ip'] ?? 'غير معروف', 'mac': data['mac'] ?? 'غير معروف', }, ), ), ); } else { throw Exception(data['message'] ?? 'فشل تسجيل الدخول'); } } else { throw Exception('فشل الاتصال بالخادم'); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('حدث خطأ: ${e.toString()}'), backgroundColor: Colors.red, behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } } finally { if (mounted) setState(() => _isLoggingIn = false); }}
@override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.rtl, child: Scaffold( body: SafeArea( child: SingleChildScrollView( padding: const EdgeInsets.all(24.0), child: Column( children: [ const SizedBox(height: 40), Image.asset('assets/network_icon.png', height: 120, width: 120), const SizedBox(height: 32), Text( 'مرحباً بعودتك', style: Theme.of(context).textTheme.headlineSmall?.copyWith( fontWeight: FontWeight.bold, color: const Color(0xFF2E384D), ), ), const SizedBox(height: 8), Text( 'سجل الدخول للوصول إلى حسابك', style: Theme.of(context).textTheme.bodyMedium?.copyWith( color: const Color(0xFF8798AD), ), ), const SizedBox(height: 32), Form( key: _formKey, child: Column( children: [ TextFormField( controller: _usernameController, decoration: InputDecoration( labelText: 'اسم المستخدم', prefixIcon: const Icon( Icons.person_outline_rounded, color: Color(0xFFB0BAC9), ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.isEmpty) { return 'الرجاء إدخال اسم المستخدم'; } return null; }, ), const SizedBox(height: 16), TextFormField( controller: _passwordController, obscureText: _obscurePassword, decoration: InputDecoration( labelText: 'كلمة المرور', prefixIcon: const Icon( Icons.lock_outline_rounded, color: Color(0xFFB0BAC9), ), suffixIcon: IconButton( icon: Icon( _obscurePassword ? Icons.visibility_off_outlined : Icons.visibility_outlined, color: const Color(0xFFB0BAC9), ), onPressed: () { setState(() { _obscurePassword = !_obscurePassword; }); }, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide( color: Color(0xFFE0E6ED), ), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.isEmpty) { return 'الرجاء إدخال كلمة المرور'; } return null; }, ), const SizedBox(height: 24), SizedBox( width: double.infinity, height: 50, child: ElevatedButton( onPressed: _isLoggingIn ? null : _login, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF3366FF), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), elevation: 0, shadowColor: Colors.transparent, ), child: _isLoggingIn ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Text( 'تسجيل الدخول', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ], ), ), ), ), ); } }
class DashboardScreen extends StatefulWidget { final String username; final Map<String, dynamic> userData;
const DashboardScreen({ super.key, required this.username, required this.userData, });
@override State createState() => _DashboardScreenState(); }
class _DashboardScreenState extends State with WidgetsBindingObserver { bool _isLoggingOut = false; Timer? _timer; late Map<String, dynamic> _currentUserData; bool _isForegroundServiceRunning = false;
@override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _currentUserData = Map<String, dynamic>.from(widget.userData); _startPeriodicUpdate(); }
@override void dispose() { _timer?.cancel(); WidgetsBinding.instance.removeObserver(this); _stopForegroundService(); super.dispose(); }
@override void didChangeAppLifecycleState(AppLifecycleState state) { if (!mounted) return;
if (state == AppLifecycleState.paused) { _startForegroundService(); } else if (state == AppLifecycleState.resumed) { _stopForegroundService(); }}
Future _startForegroundService() async { if (_isForegroundServiceRunning) return;
await FlutterForegroundTask.startService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'جاري تحديث البيانات...', callback: startCallback, ); if (mounted) setState(() => _isForegroundServiceRunning = true);}
Future _stopForegroundService() async { await FlutterForegroundTask.stopService();
if (mounted) setState(() => _isForegroundServiceRunning = false);}
void _startPeriodicUpdate() { timer = Timer.periodic(const Duration(seconds: 5), () async { await _updateUserData(); }); }
Future _updateUserData() async { try { final response = await http .get(Uri.parse('http://172.16.0.1/status?var=json')) .timeout(const Duration(seconds: 10));
if (response.statusCode == 200) { final data = json.decode(response.body); if (data.containsKey('errors')) return; if (!mounted) return; setState(() { _currentUserData = { 'logged_in': data['logged_in'] ?? 'no', 'username': data['username'] ?? widget.username, 'mac': _decodeMacAddress(data['mac'] ?? ''), 'ip': data['ip'] ?? 'غير معروف', 'bytes_in': _formatBytes(data['bytes_in'] ?? '0'), 'bytes_out': _formatBytes(data['bytes_out'] ?? '0'), 'remain_bytes_total': _formatBytes( data['remain_bytes_total'] ?? '0', ), 'uptime': _formatUptimeExtended(data['uptime'] ?? '0s'), 'session_time_left': _formatSessionTimeLeft( data['session_time_left'] ?? 'غير محدود', ), }; }); if (_isForegroundServiceRunning) { FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'IP: ${_currentUserData['ip']} | المستلم: ${_currentUserData['bytes_in']} | المرسل: ${_currentUserData['bytes_out']} | المتبقي: ${_currentUserData['session_time_left']}', ); } } } catch (_) { if (_isForegroundServiceRunning) { FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - ${_currentUserData['username']}', notificationText: 'خطأ في تحديث البيانات', ); } }}
Future _logout() async { setState(() => _isLoggingOut = true);
try { await _stopForegroundService(); final response = await http .post( Uri.parse('http://172.16.0.1/logout'), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: {'username': widget.username}, ) .timeout(const Duration(seconds: 10)); if (response.statusCode == 200) { if (mounted) { Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (_) => const LoginScreen()), (route) => false, ); } } else { throw Exception('فشل في تسجيل الخروج'); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('حدث خطأ: ${e.toString()}'), backgroundColor: Colors.red, behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } } finally { if (mounted) { setState(() => _isLoggingOut = false); } }}
String _decodeMacAddress(String encodedMac) { return encodedMac.replaceAll('%3A', ':'); }
String formatBytes(String bytes) { try { final value = int.parse(bytes); if (value < 1024) return '{(value / 1024).toStringAsFixed(1)} كيلوبايت'; if (value < 1024 * 1024 * 1024) return '{(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت'; } catch () { return bytes; } }
String _formatUptimeExtended(String uptime) { final regex = RegExp(r'(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?'); final match = regex.firstMatch(uptime); if (match == null) return uptime;
final days = int.tryParse(match.group(1) ?? '0') ?? 0; final hours = int.tryParse(match.group(2) ?? '0') ?? 0; final minutes = int.tryParse(match.group(3) ?? '0') ?? 0; final seconds = int.tryParse(match.group(4) ?? '0') ?? 0; String result = ''; if (days > 0) result += '$days يوم '; if (hours > 0) result += '$hours ساعة '; if (minutes > 0) result += '$minutes دقيقة '; if (seconds > 0) result += '$seconds ثانية'; return result.trim();}
String _formatSessionTimeLeft(String sessionTimeLeft) { if (sessionTimeLeft == 'غير محدود') return sessionTimeLeft; return _formatUptimeExtended(sessionTimeLeft); }
@override Widget build(BuildContext context) { return WithForegroundTask( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( allowWakeLock: true, allowWifiLock: true, autoRunOnBoot: false, interval: 5000, ), child: Directionality( textDirection: TextDirection.rtl, child: Scaffold( backgroundColor: const Color(0xFFF5F7FA), appBar: AppBar( title: const Text('لوحة التحكم'), centerTitle: true, elevation: 0, backgroundColor: Colors.transparent, foregroundColor: const Color(0xFF2E384D), automaticallyImplyLeading: false, actions: [ IconButton( icon: const Icon(Icons.refresh_rounded), onPressed: _updateUserData, tooltip: 'تحديث البيانات', ), ], ), body: SafeArea( child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ _buildModernUserCard(context), const SizedBox(height: 24), Expanded( child: GridView.count( crossAxisCount: 2, childAspectRatio: 1.1, crossAxisSpacing: 16, mainAxisSpacing: 16, children: [ _buildModernStatCard( icon: Icons.timer_rounded, title: 'مدة الاتصال', value: _currentUserData['uptime'] ?? 'غير معروف', color: const Color(0xFF3366FF), ), _buildModernStatCard( icon: Icons.download_rounded, title: 'البيانات المستلمة', value: _currentUserData['bytes_in'] ?? '0', color: const Color(0xFF00C1D4), ), _buildModernStatCard( icon: Icons.upload_rounded, title: 'البيانات المرسلة', value: _currentUserData['bytes_out'] ?? '0', color: const Color(0xFFFF8A34), ), _buildModernStatCard( icon: Icons.access_time_filled_rounded, title: 'الوقت المتبقي', value: _currentUserData['session_time_left'] ?? 'غير محدود', color: const Color(0xFF50B83C), ), _buildModernStatCard( icon: Icons.data_usage_rounded, title: 'البيانات المتبقية', value: _currentUserData['remain_bytes_total'] ?? '0', color: const Color(0xFF9C6ADE), ), _buildModernStatCard( icon: Icons.network_check_rounded, title: 'حالة الاتصال', value: 'نشط', color: const Color(0xFFF7C948), ), ], ), ), const SizedBox(height: 16), SizedBox( width: double.infinity, child: ElevatedButton.icon( onPressed: _isLoggingOut ? null : _logout, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFFFF453A), foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(vertical: 16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), elevation: 0, ), icon: _isLoggingOut ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator( color: Colors.white, strokeWidth: 2, ), ) : const Icon(Icons.logout_rounded, size: 20), label: Text( _isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج', style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ), ), ), ); }
Widget _buildModernUserCard(BuildContext context) { return Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(16), color: Colors.white, boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.1), blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Padding( padding: const EdgeInsets.all(16), child: Column( children: [ Row( children: [ Container( width: 60, height: 60, decoration: BoxDecoration( color: const Color(0xFF3366FF).withOpacity(0.1), shape: BoxShape.circle, ), child: const Icon( Icons.person_rounded, size: 30, color: Color(0xFF3366FF), ), ), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _currentUserData['username'] ?? widget.username, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, fontFamily: 'Tajawal', color: Color(0xFF2E384D), ), maxLines: 1, overflow: TextOverflow.ellipsis, ), const SizedBox(height: 4), const Text( 'مستخدم Hotspot', style: TextStyle( fontSize: 14, color: Color(0xFF8798AD), fontFamily: 'Tajawal', ), ), ], ), ), ], ), const SizedBox(height: 16), Divider(color: Colors.grey.withOpacity(0.2), height: 1), const SizedBox(height: 12), _buildModernInfoRow( Icons.wifi_rounded, 'عنوان IP:', _currentUserData['ip'] ?? 'غير معروف', const Color(0xFF2E384D), ), _buildModernInfoRow( Icons.device_hub_rounded, 'عنوان MAC:', _currentUserData['mac'] ?? 'غير معروف', const Color(0xFF2E384D), ), ], ), ), ); }
Widget _buildModernInfoRow( IconData icon, String label, String value, Color color, ) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: Row( children: [ Icon(icon, size: 20, color: color.withOpacity(0.6)), const SizedBox(width: 12), Text( label, style: TextStyle( fontWeight: FontWeight.bold, fontFamily: 'Tajawal', fontSize: 15, color: color.withOpacity(0.8), ), ), const SizedBox(width: 8), Expanded( child: Text( value, style: TextStyle( color: color, overflow: TextOverflow.ellipsis, fontFamily: 'Tajawal', ), ), ), ], ), ); }
Widget _buildModernStatCard({ required IconData icon, required String title, required String value, required Color color, }) { return Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(16), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.1), blurRadius: 10, offset: const Offset(0, 5), ), ], ), child: Padding( padding: const EdgeInsets.all(16), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: color.withOpacity(0.1), borderRadius: BorderRadius.circular(12), ), child: Icon(icon, size: 24, color: color), ), const SizedBox(height: 12), Text( value, style: const TextStyle( fontFamily: 'Tajawal', fontSize: 16, fontWeight: FontWeight.bold, color: Color(0xFF2E384D), ), ), const SizedBox(height: 4), Text( title, style: const TextStyle( fontFamily: 'Tajawal', fontSize: 13, color: Color(0xFF8798AD), ), ), ], ), ), ); } }
// بدء خدمة الـ foreground task @pragma('vm:entry-point') void startCallback() { FlutterForegroundTask.setTaskHandler(NetworkStatusTaskHandler()); }
class NetworkStatusTaskHandler extends TaskHandler { @override Future onStart(DateTime timestamp, TaskStarter taskStarter) async { // يمكن إضافة إعدادات أولية عند بدء المهمة }
@override Future onEvent(DateTime timestamp) async { try { final response = await http .get(Uri.parse('http://172.16.0.1/status?var=json')) .timeout(const Duration(seconds: 10));
if (response.statusCode == 200) { final data = json.decode(response.body); if (data.containsKey('errors')) return; final username = data['username'] ?? 'غير معروف'; final ip = data['ip'] ?? 'غير معروف'; final bytesIn = _formatBytes(data['bytes_in'] ?? '0'); final bytesOut = _formatBytes(data['bytes_out'] ?? '0'); final sessionTimeLeft = data['session_time_left'] ?? 'غير محدود'; await FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة - $username', notificationText: 'IP: $ip | المستلم: $bytesIn | المرسل: $bytesOut | المتبقي: $sessionTimeLeft', ); } } catch (_) { await FlutterForegroundTask.updateService( notificationTitle: 'حالة الشبكة', notificationText: 'خطأ في تحديث البيانات', ); }}
@override void onRepeatEvent(DateTime timestamp) { // يمكن تركها فارغة أو إضافة مهام غير متزامنة }
@override Future onDestroy(DateTime timestamp, bool isOnMainThread) async { // تنظيف الموارد عند إنهاء المهمة, إذا لزم الأمر }
static String formatBytes(String bytes) { try { final value = int.parse(bytes); if (value < 1024) return '{(value / 1024).toStringAsFixed(1)} كيلوبايت'; if (value < 1024 * 1024 * 1024) return '{(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت'; } catch () { return bytes; } } }
- Assistant
المشكلة التي تواجهها غالبًا تتعلق بالتوافق مع إصدار مكتبة
flutter_foreground_taskالذي تستخدمه، لأن الكائناتAndroidNotificationOptionsوForegroundTaskOptionsوالحقول داخلها مثلchannelImportanceوintervalتختلف حسب إصدار المكتبة.
1. تأكد من إصدار مكتبة
flutter_foreground_taskفي ملفpubspec.yamlإذا كنت تستخدم كود:
androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, interval: 5000, ),فاعليك استخدام إصدار مكتبة 9.x.x (مثل 9.1.0)، وليس 10.x أو أحدث، لأن الإصدار 10 وما فوق يغير الواجهات.
2. في pubspec.yaml
اضبط النسخة بهذا الشكل (مثال لأحدث إصدار 9 متوافق مع الكود):
dependencies: flutter_foreground_task: ^9.3.0ثم شغّل:
flutter pub get
3. إذا ما زالت تظهر أخطاء، راجع هذه النقاط:
- لا تستخدم
constمع كائناتAndroidNotificationOptionsأوForegroundTaskOptionsفي الإصدارات 9.x - استورد الحزم اللازمة
import 'package:flutter_foreground_task/flutter_foreground_task.dart'; - تأكد أن
channelImportanceمكتوب بشكل صحيح (أحرف ونوعهNotificationImportanceوليسNotificationChannelImportance)
4. مثال كامل مُبسّط لـ 9.x:
void main() async { WidgetsFlutterBinding.ensureInitialized(); await FlutterForegroundTask.init( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( autoRunOnBoot: false, allowWakeLock: true, allowWifiLock: true, interval: 5000, ), ); runApp(const MyApp()); }وفي
WithForegroundTask:return WithForegroundTask( androidNotificationOptions: AndroidNotificationOptions( channelId: 'network_monitor_channel', channelName: 'Network Monitor', channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق', channelImportance: NotificationImportance.DEFAULT, ), iosNotificationOptions: IOSNotificationOptions( showNotification: true, playSound: false, ), foregroundTaskOptions: ForegroundTaskOptions( allowWakeLock: true, allowWifiLock: true, autoRunOnBoot: false, interval: 5000, ), child: ... );
5. تأكد من عدم تمرير
constقبل هذه الكائناتمثال خاطئ:
await FlutterForegroundTask.init( androidNotificationOptions: const AndroidNotificationOptions( // خطأ هنا! ... ), ... );
6. ملخص الحل
- استخدم
flutter_foreground_taskبالإصدار 9.x (مثل 9.3.0). - لا تستخدم
constمع كائنات خيارات الخدمة. - استخدم
NotificationImportance(وليس NotificationChannelImportance). - استخدم
intervalكعدد صحيح (الميلي ثانية) فيForegroundTaskOptions. - أعد تشغيل IDE وتنظيف المشروع إن لزم (flutter clean).
إذا أعطيتني تفاصيل الخطأ بالتحديد (مثلاً نص الخطأ من الرسائل)، يمكنني مساعدتك بشكل أدق في إصلاح هذا الخطأ بالتحديد.
- لا تستخدم