اريد حل مشكلة تسجيل الخروج اريد ان يقوم بارجاعي الى صفحة… · The Chat Archive
Explore اريد حل مشكلة تسجيل الخروج اريد ان يقوم بارجاعي الى صفحة التسجيل الكود import… Save Share Download ▾ Reportاريد حل مشكلة تسجيل الخروج اريد ان يقوم بارجاعي الى صفحة التسجيل
الكود
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const HotspotApp());
}
class HotspotApp extends StatelessWidget {
const HotspotApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
locale: const Locale('ar'),
debugShowCheckedModeBanner: false,
title: 'MikroTik Hotspot',
theme: ThemeData(
fontFamily: 'Tajawal', // استعمال الخط المحلي
primarySwatch: Colors.blue,
colorScheme: ColorScheme.fromSwatch(
primarySwatch: Colors.blue,
accentColor: Colors.blueAccent,
brightness: Brightness.light,
).copyWith(secondary: const Color(0xFF1565C0)),
scaffoldBackgroundColor: const Color(0xFFF5F9FF),
appBarTheme: const AppBarTheme(
elevation: 0,
backgroundColor: Color(0xFF1565C0),
iconTheme: IconThemeData(color: Colors.white),
titleTextStyle: TextStyle(
fontFamily: 'Tajawal',
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
cardTheme: CardTheme(
elevation: 6,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
color: Colors.white,
shadowColor: Colors.grey.withOpacity(0.2),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: Colors.white,
contentPadding: const EdgeInsets.symmetric(
vertical: 16,
horizontal: 20,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 16),
labelStyle: TextStyle(color: Colors.grey[800]),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF1565C0),
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
textStyle: const TextStyle(
fontFamily: 'Tajawal',
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
textTheme: const TextTheme(
bodyMedium: TextStyle(fontFamily: 'Tajawal'),
bodyLarge: TextStyle(fontFamily: 'Tajawal'),
labelLarge: TextStyle(fontFamily: 'Tajawal'),
titleMedium: TextStyle(fontFamily: 'Tajawal'),
),
),
builder: (context, child) {
return Directionality(textDirection: TextDirection.rtl, child: child!);
},
home: const SplashScreen(),
);
}
}
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
@override
State createState() => _SplashScreenState();
}
class _SplashScreenState extends State
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation _animation;
@override
void initState() {
super.initState();
Show full message · 954 lines Assistant2025-05-24 17:20 UTC Copy response
اعطيني الكود الكامل لاقوم باستخدامة مباشرة لا تقوم بنسيان اي جزء
Assistant2025-05-24 17:22 UTC Copy response
اريد ان تقوم بتقسيم الكود الى ملفين ملف لل splash screen والتسجيل وملف لواجهه لوحة التحكم
Assistant2025-05-24 17:24 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 3 (6 messages)
Language en
Conversation date May 24, 2025
Added to archive Nov 16, 2026
ID 01m7h42vn76kk54e41ekjkqbhxSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 17171bac40e1fdb7d2b687411d57a24b
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1400),
);
_animation = CurvedAnimation(parent: _controller, curve: Curves.easeInOut);
_controller.repeat(reverse: true);
Timer(const Duration(seconds: 3), () {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const AuthCheckScreen()),
);
});
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF1565C0),
body: Center(
child: FadeTransition(
opacity: _animation,
child: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.wifi, size: 120, color: Colors.white),
SizedBox(height: 20),
Text(
'شبكة الواي فاي',
style: TextStyle(
fontFamily: 'Tajawal',
color: Colors.white,
fontSize: 26,
fontWeight: FontWeight.bold,
letterSpacing: 1.3,
),
),
SizedBox(height: 40),
SpinKitFadingCircle(color: Colors.white, size: 50.0),
],
),
),
),
);
}
}
class AuthCheckScreen extends StatefulWidget {
const AuthCheckScreen({Key? key}) : super(key: key);
@override
State createState() => _AuthCheckScreenState();
}
class _AuthCheckScreenState extends State {
bool _checking = true;
String? _username;
Map<String, String> cookies = {};
Future<Map<String, dynamic>> _fetchUserData() async {
try {
final response = await http
.get(Uri.parse('http://172.16.0.1/status?var=json '))
.timeout(const Duration(seconds: 10));
_updateCookies(response);
code Copy code
if (response.statusCode == 200) {
final data = json.decode(response.body);
if (data.containsKey('errors')) {
return {'error': data['errors'].toString()};
}
return data;
} else {
return {'error': 'خطأ في استجابة الراوتر: ${response.statusCode}'};
}
} catch (e) {
return {'error': 'تعذر الاتصال بالراوتر: ${e.toString()}'};
}
void _updateCookies(http.Response response) {
final setCookie = response.headers['set-cookie'];
if (setCookie != null) {
final parts = setCookie.split(',');
for (var part in parts) {
var cookieItems = part.split(';');
if (cookieItems.isNotEmpty) {
var keyValue = cookieItems[0].split('=');
if (keyValue.length == 2) {
cookies[keyValue[0].trim()] = keyValue[1];
}
}
}
}
}
String _getCookieHeader() {
String cookie = '';
cookies.forEach((key, value) {
if (cookie.isNotEmpty) cookie += '; ';
cookie += 'k e y = key= k ey = value';
});
return cookie;
}
@override
void initState() {
super.initState();
_checkLogin();
}
Future _checkLogin() async {
final data = await _fetchUserData();
code Copy code
if (data.containsKey('error')) {
if (mounted) {
setState(() {
_checking = false;
_username = null;
});
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const LoginScreen()),
);
}
return;
}
final loggedIn = data['logged_in'] ?? 'no';
if (loggedIn == 'yes' || loggedIn == 'on') {
if (mounted) {
final username = data['username'] ?? 'مستخدم';
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder:
(_) => DashboardScreen(
username: username,
userData: {
'logged_in': loggedIn,
'username': username,
'mac': data['mac'] ?? '',
'ip': data['ip'] ?? '',
'bytes_in': data['bytes_in'] ?? '0',
'bytes_out': data['bytes_out'] ?? '0',
'remain_bytes_total': data['remain_bytes_total'] ?? '0',
'uptime': data['uptime'] ?? '0s',
'session_time_left':
data['session_time_left'] ?? 'غير محدود',
},
),
),
);
}
} else {
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const LoginScreen()),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
_checking
? const SpinKitCircle(color: Color(0xFF1565C0), size: 60)
: const Text('جارِ التحقق من حالة تسجيل الدخول...'),
),
);
}
}
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State createState() => _LoginScreenState();
}
class _LoginScreenState extends State {
final TextEditingController _usernameController = TextEditingController();
bool _isLoading = false;
String _message = '';
bool _showMessage = false;
bool _isError = false;
Map<String, String> cookies = {};
void _updateCookies(http.Response response) {
final setCookie = response.headers['set-cookie'];
if (setCookie != null) {
final parts = setCookie.split(',');
for (var part in parts) {
var cookieItems = part.split(';');
if (cookieItems.isNotEmpty) {
var keyValue = cookieItems[0].split('=');
if (keyValue.length == 2) {
cookies[keyValue[0].trim()] = keyValue[1];
}
}
}
}
}
String _getCookieHeader() {
String cookie = '';
cookies.forEach((key, value) {
if (cookie.isNotEmpty) cookie += '; ';
cookie += 'k e y = key= k ey = value';
});
return cookie;
}
void _showStatusMessage(String message, {bool isError = false}) {
setState(() {
_message = message;
_showMessage = true;
_isError = isError;
});
Future.delayed(const Duration(seconds: 4), () {
if (mounted) setState(() => _showMessage = false);
});
}
Future _login() async {
if (_usernameController.text.isEmpty) {
_showStatusMessage('يجب إدخال اسم المستخدم', isError: true);
return;
}
code Copy code
setState(() {
_isLoading = true;
_showMessage = false;
cookies.clear();
});
try {
final responseGet = await http
.get(Uri.parse('http://172.16.0.1/status?var=json'))
.timeout(const Duration(seconds: 10));
_updateCookies(responseGet);
final loginResponse = await http
.post(
Uri.parse('http://172.16.0.1/login'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': _getCookieHeader(),
},
body: {'username': _usernameController.text, 'password': ''},
)
.timeout(const Duration(seconds: 10));
_updateCookies(loginResponse);
final responseAfterLogin = await http
.get(
Uri.parse('http://172.16.0.1/status?var=json'),
headers: {'Cookie': _getCookieHeader()},
)
.timeout(const Duration(seconds: 10));
final data = json.decode(responseAfterLogin.body);
final loggedInStatus = data['logged_in'] ?? 'no';
if (loggedInStatus == 'yes' || loggedInStatus == 'on') {
_showStatusMessage('تم تسجيل الدخول بنجاح', isError: false);
if (mounted) {
final username = data['username'] ?? _usernameController.text;
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder:
(context) => DashboardScreen(
username: username,
userData: {
'logged_in': loggedInStatus,
'username': username,
'mac': data['mac'] ?? '',
'ip': data['ip'] ?? '',
'bytes_in': data['bytes_in'] ?? '0',
'bytes_out': data['bytes_out'] ?? '0',
'remain_bytes_total': data['remain_bytes_total'] ?? '0',
'uptime': data['uptime'] ?? '0s',
'session_time_left':
data['session_time_left'] ?? 'غير محدود',
},
),
),
);
}
} else {
_showStatusMessage(
'فشل تسجيل الدخول. تأكد من صحة البيانات.',
isError: true,
);
}
} catch (e) {
_showStatusMessage('حدث خطأ: ${e.toString()}', isError: true);
} finally {
if (mounted) {
setState(() => _isLoading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('تسجيل الدخول'), centerTitle: true),
body: Stack(
children: [
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF1565C0), Color(0xFF0D47A1)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 24,
),
child: Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 28,
vertical: 36,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.wifi,
size: 100,
color: Theme.of(context).primaryColor,
),
const SizedBox(height: 24),
Text(
'مرحباً بك في شبكة الواي فاي',
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
fontFamily: 'Tajawal',
color: Colors.black87,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
TextField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'اسم المستخدم',
prefixIcon: Icon(Icons.person),
),
style: const TextStyle(fontSize: 18),
),
const SizedBox(height: 36),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _isLoading ? null : _login,
child:
_isLoading
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 3,
),
)
: const Text('تسجيل الدخول'),
),
),
],
),
),
),
),
),
),
if (_showMessage)
Positioned(
bottom: 20,
left: 20,
right: 20,
child: AnimatedOpacity(
opacity: _showMessage ? 1 : 0,
duration: const Duration(milliseconds: 300),
child: Material(
elevation: 6,
borderRadius: BorderRadius.circular(12),
color: _isError ? Colors.red[50] : Colors.green[50],
child: Container(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Icon(
_isError ? Icons.error_outline : Icons.check_circle,
color: _isError ? Colors.red : Colors.green,
),
const SizedBox(width: 12),
Expanded(
child: Text(
_message,
style: TextStyle(
color:
_isError
? Colors.red[800]
: Colors.green[800],
fontWeight: FontWeight.bold,
),
),
),
IconButton(
onPressed: () => setState(() => _showMessage = false),
icon: const Icon(Icons.close),
color: _isError ? Colors.red : Colors.green,
),
],
),
),
),
),
),
],
),
);
}
}
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 {
bool _isLoggingOut = false;
Timer? _timer;
late Map<String, dynamic> _currentUserData;
@override
void initState() {
super.initState();
_currentUserData = widget.userData;
_startPeriodicUpdate();
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
void _startPeriodicUpdate() {
_timer = Timer.periodic(const Duration(seconds: 1), (timer) async {
await _updateUserData();
});
}
code Copy code
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'] ?? 'غير محدود',
),
};
});
}
} catch (_) {
// تجاهل الأخطاء في التحديث الدوري
}
Future _logout() async {
setState(() => _isLoggingOut = true);
code Copy code
try {
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.pop(context);
}
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('فشل في تسجيل الخروج'),
backgroundColor: Colors.red,
),
);
}
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('حدث خطأ: ${e.toString()}'),
backgroundColor: Colors.red,
),
);
}
} 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 'v a l u e باي ت ′ ; i f ( v a l u e < 1024 ∗ 1024 ) r e t u r n ′ value بايت';
if (value < 1024 * 1024)
return ' v a l u e باي ت ′ ; i f ( v a l u e < 1024 ∗ 1024 ) r e t u r n ′ {(value / 1024).toStringAsFixed(1)} كيلوبايت';
if (value < 1024 * 1024 * 1024)
return '( v a l u e / ( 1024 ∗ 1024 ) ) . t o S t r i n g A s F i x e d ( 1 ) ميجاباي ت ′ ; r e t u r n ′ {(value / (1024 * 1024)).toStringAsFixed(1)} ميجابايت';
return ' ( v a l u e / ( 1024 ∗ 1024 )) . t o S t r in g A s F i x e d {(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت';
} catch (e) {
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;
code Copy code
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 Scaffold(
appBar: AppBar(
title: const Text('لوحة التحكم'),
centerTitle: true,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _updateUserData,
),
],
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildUserCard(context),
const SizedBox(height: 16),
Expanded(
child: GridView.count(
crossAxisCount: 2,
childAspectRatio: 1.2,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
children: [
_buildStatCard(
icon: Icons.timer,
title: 'مدة الاتصال',
value: _currentUserData['uptime'] ?? 'غير معروف',
color: Colors.blue,
),
_buildStatCard(
icon: Icons.download,
title: 'البيانات المستلمة',
value: _currentUserData['bytes_in'] ?? '0',
color: Colors.purple,
),
_buildStatCard(
icon: Icons.upload,
title: 'البيانات المرسلة',
value: _currentUserData['bytes_out'] ?? '0',
color: Colors.orange,
),
_buildStatCard(
icon: Icons.access_time,
title: 'الوقت المتبقي',
value: _currentUserData['session_time_left'] ?? 'غير محدود',
color: Colors.green,
),
_buildStatCard(
icon: Icons.sd_storage,
title: 'البيانات المتبقية',
value: _currentUserData['remain_bytes_total'] ?? '0',
color: Colors.teal,
),
],
),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: _isLoggingOut ? null : _logout,
icon:
_isLoggingOut
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2,
),
)
: const Icon(Icons.logout),
label: Text(
_isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج',
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red[400],
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
],
),
),
);
}
Widget _buildUserCard(BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Colors.blue[50],
shape: BoxShape.circle,
),
child: const Icon(Icons.person, size: 30, color: Colors.blue),
),
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',
),
),
const SizedBox(height: 4),
Text(
'مستخدم Hotspot',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
fontFamily: 'Tajawal',
),
),
],
),
),
],
),
const SizedBox(height: 16),
_buildInfoRow(
Icons.computer,
'عنوان IP:',
_currentUserData['ip'] ?? 'غير معروف',
),
_buildInfoRow(
Icons.settings_ethernet,
'عنوان MAC:',
_currentUserData['mac'] ?? 'غير معروف',
),
],
),
),
);
}
Widget _buildInfoRow(IconData icon, String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
Icon(icon, size: 20, color: Colors.blue),
const SizedBox(width: 12),
Text(
label,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Tajawal',
fontSize: 16,
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
value,
style: const TextStyle(
color: Colors.grey,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
Widget _buildStatCard({
required IconData icon,
required String title,
required String value,
required Color color,
}) {
return Card(
elevation: 5,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: color.withOpacity(0.15),
shape: BoxShape.circle,
),
child: Icon(icon, size: 28, color: color),
),
const SizedBox(height: 14),
Text(
value,
style: const TextStyle(
fontFamily: 'Tajawal',
fontSize: 18,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 5),
Text(
title,
style: TextStyle(
fontFamily: 'Tajawal',
fontSize: 14,
color: Colors.grey[600],
),
textAlign: TextAlign.center,
),
],
),
),
);
}
}
لمعالجة مشكلة "تسجيل الخروج" بحيث يتم نقلك مباشرةً إلى صفحة تسجيل الدخول بعد تسجيل الخروج، تحتاج إلى تعديل دالة _logout في DashboardScreen بحيث بعد تأكيد أن عملية تسجيل الخروج تمت بنجاح، تقوم باستخدام Navigator.pushReplacement لتوجيه المستخدم إلى صفحة LoginScreen.
في كودك الحالي داخل دالة _logout في صفحة لوحة التحكم (DashboardScreen)، تستخدم هذا السطر:
dart Copy code
Navigator.pop(context);
وهذا يعيدك للصفحة السابقة (على الأرجح شاشة التحقق AuthCheckScreen أو غيرها)، ولكنه لا يعيدك مباشرةً إلى صفحة تسجيل الدخول.
الحل:
قم بتغيير هذا السطر إلى:
dart Copy code
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (_) => const LoginScreen()),
(route) => false,
);
شرح:
pushAndRemoveUntil يدفع شاشة جديدة (صفحة تسجيل الدخول) ويزيل كافة الشاشات السابقة من الـ stack، مما يضمن أنه عند الضغط على زر "الرجوع" لن يعود المستخدم إلى الشاشة السابقة.
(route) => false تعني إزالة جميع الشاشات السابقة.
التعديل الكامل على دالة _logout:
dart Copy code
Future<void> _logout() async {
setState(() => _isLoggingOut = true);
try {
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 {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('فشل في تسجيل الخروج'),
backgroundColor: Colors.red,
),
);
}
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('حدث خطأ: ${e.toString()}'),
backgroundColor: Colors.red,
),
);
}
} finally {
if (mounted) {
setState(() => _isLoggingOut = false);
}
}
}
ملاحظة مهمة:
بعد تسجيل الخروج، من الأفضل تنظيف الكوكيز أو أي حالة تخزين متعلقة بجلسة المستخدم إذا كنت تخزنها محليًا أو في المتغيرات.
الكود الحالي لا يظهر أنك تخزن حالة الدخول في مكان مشترك، فإذا كان لديك طريقة لتتبع حالة الجلسة، تأكد من تنظيفها أيضًا عند تسجيل الخروج.
إذا احتجت أي مساعدة أخرى في تحسين عملية تسجيل الدخول أو تسجيل الخروج، لا تتردد بالسؤال!
بالطبع! فيما يلي الكود الكامل لصفحة DashboardScreen مع تعديل دالة _logout لتوجيه المستخدم إلى صفحة تسجيل الدخول مباشرة عند تسجيل الخروج، مع الحفاظ على جميع أجزاء الكود كما هو مع التعديل المطلوب فقط.
dart Copy code
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> {
bool _isLoggingOut = false;
Timer? _timer;
late Map<String, dynamic> _currentUserData;
@override
void initState() {
super.initState();
_currentUserData = widget.userData;
_startPeriodicUpdate();
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
void _startPeriodicUpdate() {
_timer = Timer.periodic(const Duration(seconds: 1), (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'] ?? 'غير محدود',
),
};
});
}
} catch (_) {
// تجاهل الأخطاء في التحديث الدوري
}
}
Future<void> _logout() async {
setState(() => _isLoggingOut = true);
try {
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 {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('فشل في تسجيل الخروج'),
backgroundColor: Colors.red,
),
);
}
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('حدث خطأ: ${e.toString()}'),
backgroundColor: Colors.red,
),
);
}
} 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 (e) {
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 Scaffold(
appBar: AppBar(
title: const Text('لوحة التحكم'),
centerTitle: true,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _updateUserData,
),
],
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildUserCard(context),
const SizedBox(height: 16),
Expanded(
child: GridView.count(
crossAxisCount: 2,
childAspectRatio: 1.2,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
children: [
_buildStatCard(
icon: Icons.timer,
title: 'مدة الاتصال',
value: _currentUserData['uptime'] ?? 'غير معروف',
color: Colors.blue,
),
_buildStatCard(
icon: Icons.download,
title: 'البيانات المستلمة',
value: _currentUserData['bytes_in'] ?? '0',
color: Colors.purple,
),
_buildStatCard(
icon: Icons.upload,
title: 'البيانات المرسلة',
value: _currentUserData['bytes_out'] ?? '0',
color: Colors.orange,
),
_buildStatCard(
icon: Icons.access_time,
title: 'الوقت المتبقي',
value: _currentUserData['session_time_left'] ?? 'غير محدود',
color: Colors.green,
),
_buildStatCard(
icon: Icons.sd_storage,
title: 'البيانات المتبقية',
value: _currentUserData['remain_bytes_total'] ?? '0',
color: Colors.teal,
),
],
),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: _isLoggingOut ? null : _logout,
icon: _isLoggingOut
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2,
),
)
: const Icon(Icons.logout),
label: Text(
_isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج',
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red[400],
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
],
),
),
);
}
Widget _buildUserCard(BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Colors.blue[50],
shape: BoxShape.circle,
),
child: const Icon(Icons.person, size: 30, color: Colors.blue),
),
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',
),
),
const SizedBox(height: 4),
Text(
'مستخدم Hotspot',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
fontFamily: 'Tajawal',
),
),
],
),
),
],
),
const SizedBox(height: 16),
_buildInfoRow(
Icons.computer,
'عنوان IP:',
_currentUserData['ip'] ?? 'غير معروف',
),
_buildInfoRow(
Icons.settings_ethernet,
'عنوان MAC:',
_currentUserData['mac'] ?? 'غير معروف',
),
],
),
),
);
}
Widget _buildInfoRow(IconData icon, String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
Icon(icon, size: 20, color: Colors.blue),
const SizedBox(width: 12),
Text(
label,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Tajawal',
fontSize: 16,
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
value,
style: const TextStyle(
color: Colors.grey,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
Widget _buildStatCard({
required IconData icon,
required String title,
required String value,
required Color color,
}) {
return Card(
elevation: 5,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: color.withOpacity(0.15),
shape: BoxShape.circle,
),
child: Icon(icon, size: 28, color: color),
),
const SizedBox(height: 14),
Text(
value,
style: const TextStyle(
fontFamily: 'Tajawal',
fontSize: 18,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 5),
Text(
title,
style: TextStyle(
fontFamily: 'Tajawal',
fontSize: 14,
color: Colors.grey[600],
),
textAlign: TextAlign.center,
),
],
),
),
);
}
}
ما الذي تم تغييره فقط؟
dart Copy code
Navigator.pop(context);
تم استبدالها بـ
dart Copy code
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (_) => const LoginScreen()),
(route) => false,
);
وهذا يضمن أنه بعد تسجيل الخروج، يتم إعادة توجيه المستخدم إلى شاشة تسجيل الدخول مع إزالة جميع شاشات التطبيق السابقة من التاريخ (stack).
إذا كنت تريد نسخة كاملة من جميع الشاشات أو أي جزء آخر، فقط أخبرني.
Show full message · 427 lines بالطبع! سأقسم لك الكود إلى ملفين رئيسيين:
ملف auth_screens.dart يحتوي على:
SplashScreen
AuthCheckScreen
LoginScreen
ملف dashboard_screen.dart يحتوي على:
1. ملف auth_screens.dart
dart Copy code
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:http/http.dart' as http;
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1400),
);
_animation = CurvedAnimation(parent: _controller, curve: Curves.easeInOut);
_controller.repeat(reverse: true);
Timer(const Duration(seconds: 3), () {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const AuthCheckScreen()),
);
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF1565C0),
body: Center(
child: FadeTransition(
opacity: _animation,
child: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.wifi, size: 120, color: Colors.white),
SizedBox(height: 20),
Text(
'شبكة الواي فاي',
style: TextStyle(
fontFamily: 'Tajawal',
color: Colors.white,
fontSize: 26,
fontWeight: FontWeight.bold,
letterSpacing: 1.3,
),
),
SizedBox(height: 40),
SpinKitFadingCircle(color: Colors.white, size: 50.0),
],
),
),
),
);
}
}
class AuthCheckScreen extends StatefulWidget {
const AuthCheckScreen({Key? key}) : super(key: key);
@override
State<AuthCheckScreen> createState() => _AuthCheckScreenState();
}
class _AuthCheckScreenState extends State<AuthCheckScreen> {
bool _checking = true;
String? _username;
Map<String, String> cookies = {};
Future<Map<String, dynamic>> _fetchUserData() async {
try {
final response = await http
.get(Uri.parse('http://172.16.0.1/status?var=json'))
.timeout(const Duration(seconds: 10));
_updateCookies(response);
if (response.statusCode == 200) {
final data = json.decode(response.body);
if (data.containsKey('errors')) {
return {'error': data['errors'].toString()};
}
return data;
} else {
return {'error': 'خطأ في استجابة الراوتر: ${response.statusCode}'};
}
} catch (e) {
return {'error': 'تعذر الاتصال بالراوتر: ${e.toString()}'};
}
}
void _updateCookies(http.Response response) {
final setCookie = response.headers['set-cookie'];
if (setCookie != null) {
final parts = setCookie.split(',');
for (var part in parts) {
var cookieItems = part.split(';');
if (cookieItems.isNotEmpty) {
var keyValue = cookieItems[0].split('=');
if (keyValue.length == 2) {
cookies[keyValue[0].trim()] = keyValue[1];
}
}
}
}
}
String _getCookieHeader() {
String cookie = '';
cookies.forEach((key, value) {
if (cookie.isNotEmpty) cookie += '; ';
cookie += '$key=$value';
});
return cookie;
}
@override
void initState() {
super.initState();
_checkLogin();
}
Future<void> _checkLogin() async {
final data = await _fetchUserData();
if (data.containsKey('error')) {
if (mounted) {
setState(() {
_checking = false;
_username = null;
});
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const LoginScreen()),
);
}
return;
}
final loggedIn = data['logged_in'] ?? 'no';
if (loggedIn == 'yes' || loggedIn == 'on') {
if (mounted) {
final username = data['username'] ?? 'مستخدم';
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder:
(_) => DashboardScreen(
username: username,
userData: {
'logged_in': loggedIn,
'username': username,
'mac': data['mac'] ?? '',
'ip': data['ip'] ?? '',
'bytes_in': data['bytes_in'] ?? '0',
'bytes_out': data['bytes_out'] ?? '0',
'remain_bytes_total': data['remain_bytes_total'] ?? '0',
'uptime': data['uptime'] ?? '0s',
'session_time_left':
data['session_time_left'] ?? 'غير محدود',
},
),
),
);
}
} else {
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const LoginScreen()),
);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
_checking
? const SpinKitCircle(color: Color(0xFF1565C0), size: 60)
: const Text('جارِ التحقق من حالة تسجيل الدخول...'),
),
);
}
}
// لا تنس استيراد dashboard_screen.dart لهذا السطر:
import 'dashboard_screen.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final TextEditingController _usernameController = TextEditingController();
bool _isLoading = false;
String _message = '';
bool _showMessage = false;
bool _isError = false;
Map<String, String> cookies = {};
void _updateCookies(http.Response response) {
final setCookie = response.headers['set-cookie'];
if (setCookie != null) {
final parts = setCookie.split(',');
for (var part in parts) {
var cookieItems = part.split(';');
if (cookieItems.isNotEmpty) {
var keyValue = cookieItems[0].split('=');
if (keyValue.length == 2) {
cookies[keyValue[0].trim()] = keyValue[1];
}
}
}
}
}
String _getCookieHeader() {
String cookie = '';
cookies.forEach((key, value) {
if (cookie.isNotEmpty) cookie += '; ';
cookie += '$key=$value';
});
return cookie;
}
void _showStatusMessage(String message, {bool isError = false}) {
setState(() {
_message = message;
_showMessage = true;
_isError = isError;
});
Future.delayed(const Duration(seconds: 4), () {
if (mounted) setState(() => _showMessage = false);
});
}
Future<void> _login() async {
if (_usernameController.text.isEmpty) {
_showStatusMessage('يجب إدخال اسم المستخدم', isError: true);
return;
}
setState(() {
_isLoading = true;
_showMessage = false;
cookies.clear();
});
try {
final responseGet = await http
.get(Uri.parse('http://172.16.0.1/status?var=json'))
.timeout(const Duration(seconds: 10));
_updateCookies(responseGet);
final loginResponse = await http
.post(
Uri.parse('http://172.16.0.1/login'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': _getCookieHeader(),
},
body: {'username': _usernameController.text, 'password': ''},
)
.timeout(const Duration(seconds: 10));
_updateCookies(loginResponse);
final responseAfterLogin = await http
.get(
Uri.parse('http://172.16.0.1/status?var=json'),
headers: {'Cookie': _getCookieHeader()},
)
.timeout(const Duration(seconds: 10));
final data = json.decode(responseAfterLogin.body);
final loggedInStatus = data['logged_in'] ?? 'no';
if (loggedInStatus == 'yes' || loggedInStatus == 'on') {
_showStatusMessage('تم تسجيل الدخول بنجاح', isError: false);
if (mounted) {
final username = data['username'] ?? _usernameController.text;
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder:
(context) => DashboardScreen(
username: username,
userData: {
'logged_in': loggedInStatus,
'username': username,
'mac': data['mac'] ?? '',
'ip': data['ip'] ?? '',
'bytes_in': data['bytes_in'] ?? '0',
'bytes_out': data['bytes_out'] ?? '0',
'remain_bytes_total': data['remain_bytes_total'] ?? '0',
'uptime': data['uptime'] ?? '0s',
'session_time_left':
data['session_time_left'] ?? 'غير محدود',
},
),
),
);
}
} else {
_showStatusMessage(
'فشل تسجيل الدخول. تأكد من صحة البيانات.',
isError: true,
);
}
} catch (e) {
_showStatusMessage('حدث خطأ: ${e.toString()}', isError: true);
} finally {
if (mounted) {
setState(() => _isLoading = false);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('تسجيل الدخول'), centerTitle: true),
body: Stack(
children: [
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF1565C0), Color(0xFF0D47A1)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 24,
),
child: Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 28,
vertical: 36,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.wifi,
size: 100,
color: Theme.of(context).primaryColor,
),
const SizedBox(height: 24),
Text(
'مرحباً بك في شبكة الواي فاي',
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
fontFamily: 'Tajawal',
color: Colors.black87,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
TextField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'اسم المستخدم',
prefixIcon: Icon(Icons.person),
),
style: const TextStyle(fontSize: 18),
),
const SizedBox(height: 36),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _isLoading ? null : _login,
child: _isLoading
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 3,
),
)
: const Text('تسجيل الدخول'),
),
),
],
),
),
),
),
),
),
if (_showMessage)
Positioned(
bottom: 20,
left: 20,
right: 20,
child: AnimatedOpacity(
opacity: _showMessage ? 1 : 0,
duration: const Duration(milliseconds: 300),
child: Material(
elevation: 6,
borderRadius: BorderRadius.circular(12),
color: _isError ? Colors.red[50] : Colors.green[50],
child: Container(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Icon(
_isError ? Icons.error_outline : Icons.check_circle,
color: _isError ? Colors.red : Colors.green,
),
const SizedBox(width: 12),
Expanded(
child: Text(
_message,
style: TextStyle(
color:
_isError ? Colors.red[800] : Colors.green[800],
fontWeight: FontWeight.bold,
),
),
),
IconButton(
onPressed: () => setState(() => _showMessage = false),
icon: const Icon(Icons.close),
color: _isError ? Colors.red : Colors.green,
),
],
),
),
),
),
),
],
),
);
}
}
2. ملف dashboard_screen.dart
كيفية الاستخدام:
في ملف main.dart يجب استيراد auth_screens.dart لأن نقطة البداية هي SplashScreen:
dart Copy code
import 'package:flutter/material.dart';
import 'auth_screens.dart';
void main() {
runApp(const HotspotApp());
}
class HotspotApp extends StatelessWidget {
const HotspotApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
locale: const Locale('ar'),
debugShowCheckedModeBanner: false,
title: 'MikroTik Hotspot',
theme: ThemeData(
fontFamily: 'Tajawal',
// باقي إعدادات الثيم كما في كودك الأصلي
),
builder: (context, child) {
return Directionality(textDirection: TextDirection.rtl, child: child!);
},
home: const SplashScreen(),
);
}
}
بحيث:
عند بدء التطبيق يتم عرض SplashScreen.
بعده يتم التحقق من حالة تسجيل الدخول عبر AuthCheckScreen.
حسب الحالة يتم التوجه لصفحة LoginScreen أو DashboardScreen.
وعلى لوحة التحكم عند تسجيل الخروج نرجع مباشرة لشاشة تسجيل الدخول مع إزالة الشاشات السابقة.
إذا أردت أو تحتاج لأي مساعدة إضافية مثل إضافة ملف main.dart كامل أو تنظيم إضافي، أخبرني فقط!
Show full message · 949 lines Copy first response
Not yet included in a published release.
(
1
)
ميجاباي
ت ′
;
r
e
t
u
r
n ′
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'auth_screens.dart'; // لتتمكن من الوصول إلى LoginScreen
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> {
bool _isLoggingOut = false;
Timer? _timer;
late Map<String, dynamic> _currentUserData;
@override
void initState() {
super.initState();
_currentUserData = widget.userData;
_startPeriodicUpdate();
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
void _startPeriodicUpdate() {
_timer = Timer.periodic(const Duration(seconds: 1), (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'] ?? 'غير محدود',
),
};
});
}
} catch (_) {
// تجاهل الأخطاء في التحديث الدوري
}
}
Future<void> _logout() async {
setState(() => _isLoggingOut = true);
try {
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 {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('فشل في تسجيل الخروج'),
backgroundColor: Colors.red,
),
);
}
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('حدث خطأ: ${e.toString()}'),
backgroundColor: Colors.red,
),
);
}
} 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 (e) {
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 Scaffold(
appBar: AppBar(
title: const Text('لوحة التحكم'),
centerTitle: true,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _updateUserData,
),
],
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildUserCard(context),
const SizedBox(height: 16),
Expanded(
child: GridView.count(
crossAxisCount: 2,
childAspectRatio: 1.2,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
children: [
_buildStatCard(
icon: Icons.timer,
title: 'مدة الاتصال',
value: _currentUserData['uptime'] ?? 'غير معروف',
color: Colors.blue,
),
_buildStatCard(
icon: Icons.download,
title: 'البيانات المستلمة',
value: _currentUserData['bytes_in'] ?? '0',
color: Colors.purple,
),
_buildStatCard(
icon: Icons.upload,
title: 'البيانات المرسلة',
value: _currentUserData['bytes_out'] ?? '0',
color: Colors.orange,
),
_buildStatCard(
icon: Icons.access_time,
title: 'الوقت المتبقي',
value: _currentUserData['session_time_left'] ?? 'غير محدود',
color: Colors.green,
),
_buildStatCard(
icon: Icons.sd_storage,
title: 'البيانات المتبقية',
value: _currentUserData['remain_bytes_total'] ?? '0',
color: Colors.teal,
),
],
),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: _isLoggingOut ? null : _logout,
icon: _isLoggingOut
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2,
),
)
: const Icon(Icons.logout),
label: Text(
_isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج',
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red[400],
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
],
),
),
);
}
Widget _buildUserCard(BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Colors.blue[50],
shape: BoxShape.circle,
),
child: const Icon(Icons.person, size: 30, color: Colors.blue),
),
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',
),
),
const SizedBox(height: 4),
Text(
'مستخدم Hotspot',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
fontFamily: 'Tajawal',
),
),
],
),
),
],
),
const SizedBox(height: 16),
_buildInfoRow(
Icons.computer,
'عنوان IP:',
_currentUserData['ip'] ?? 'غير معروف',
),
_buildInfoRow(
Icons.settings_ethernet,
'عنوان MAC:',
_currentUserData['mac'] ?? 'غير معروف',
),
],
),
),
);
}
Widget _buildInfoRow(IconData icon, String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
Icon(icon, size: 20, color: Colors.blue),
const SizedBox(width: 12),
Text(
label,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Tajawal',
fontSize: 16,
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
value,
style: const TextStyle(
color: Colors.grey,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
);
}
Widget _buildStatCard({
required IconData icon,
required String title,
required String value,
required Color color,
}) {
return Card(
elevation: 5,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: color.withOpacity(0.15),
shape: BoxShape.circle,
),
child: Icon(icon, size: 28, color: color),
),
const SizedBox(height: 14),
Text(
value,
style: const TextStyle(
fontFamily: 'Tajawal',
fontSize: 18,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 5),
Text(
title,
style: TextStyle(
fontFamily: 'Tajawal',
fontSize: 14,
color: Colors.grey[600],
),
textAlign: TextAlign.center,
),
],
),
),
);
}
}