اريد فصل كل واجهه في ملف منفرد
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.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(
title: 'MikroTik Hotspot',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
fontFamily: 'Tajawal',
scaffoldBackgroundColor: const Color(0xFFF5F9FF),
appBarTheme: const AppBarTheme(
backgroundColor: Color(0xFF1565C0),
iconTheme: IconThemeData(color: Colors.white),
titleTextStyle: TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold,
),
elevation: 0,
centerTitle: true,
),
),
home: const AuthCheckScreen(),
);
}
}
class AuthCheckScreen extends StatelessWidget {
const AuthCheckScreen({super.key});
Future<Map<String, dynamic>> fetchUserData() async {
try {
final res = await http
.get(Uri.parse('http://172.16.0.1/login?var=json'))
.timeout(const Duration(seconds: 10));
if (res.statusCode == 200) {
final data = json.decode(res.body);
if (data.containsKey('errors')) {
return {'error': data['errors'].toString()};
}
return data;
}
return {'error': 'خطأ في استجابة الراوتر: {res.statusCode}'};
} catch (e) {
return {'error': 'تعذر الاتصال بالراوتر: e'};
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder<Map<String, dynamic>>(
future: fetchUserData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
if (!snapshot.hasData || snapshot.data!.containsKey('error')) {
// غير مسجل دخول
WidgetsBinding.instance.addPostFrameCallback(() {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: () => const LoginScreen()),
);
});
return const SizedBox.shrink();
}
final data = snapshot.data!;
final loggedIn = data['logged_in'] ?? 'no';
if (loggedIn == 'yes' || loggedIn == 'on') {
WidgetsBinding.instance.addPostFrameCallback(() {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder:
() => DashboardScreen(
username: data['username'] ?? 'مستخدم',
userData: data,
),
),
);
});
return const SizedBox.shrink();
} else {
WidgetsBinding.instance.addPostFrameCallback(() {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: () => const LoginScreen()),
);
});
return const SizedBox.shrink();
}
},
);
}
}
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 isError = false;
Future login() async {
if (usernameController.text.isEmpty) {
showMessage('يجب إدخال اسم المستخدم', true);
return;
}
setState(() {
isLoading = true;
message = null;
});
try {
// احصل على كوكيز البداية
final resGet = await http
.get(Uri.parse('http://172.16.0.1/login?var=json'))
.timeout(const Duration(seconds: 10));
var cookies = resGet.headers['set-cookie'] ?? '';
// تسجيل الدخول
final resLogin = await http
.post(
Uri.parse('http://172.16.0.1/login'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': cookies,
},
body: {'username': usernameController.text, 'password': ''},
)
.timeout(const Duration(seconds: 10));
cookies = resLogin.headers['set-cookie'] ?? cookies;
// تحقق من حالة تسجيل الدخول
final resStatus = await http
.get(
Uri.parse('http://172.16.0.1/login?var=json'),
headers: {'Cookie': cookies},
)
.timeout(const Duration(seconds: 10));
final data = json.decode(resStatus.body);
final loggedIn = data['logged_in'] ?? 'no';
if (loggedIn == 'yes' || loggedIn == 'on') {
showMessage('تم تسجيل الدخول بنجاح', false);
if (!mounted) return;
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder:
(_) => DashboardScreen(
username: usernameController.text,
userData: data,
),
),
);
} else {
showMessage('فشل تسجيل الدخول. تأكد من صحة البيانات.', true);
}
} catch (e) {
showMessage('حدث خطأ: $e', true);
} finally {
if (mounted) {
setState(() => isLoading = false);
}
}
}
void showMessage(String msg, bool error) {
setState(() {
message = msg;
isError = error;
});
Future.delayed(const Duration(seconds: 3), () {
if (mounted) {
setState(() {
message = null;
});
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('تسجيل الدخول')),
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF1565C0), Color(0xFF0D47A1)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Card(
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
children: [
const Icon(Icons.wifi, size: 80, color: Colors.blue),
const SizedBox(height: 20),
const Text(
'مرحباً بك في شبكة الواي فاي',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
const SizedBox(height: 24),
TextField(
controller: usernameController,
decoration: const InputDecoration(
labelText: 'اسم المستخدم',
prefixIcon: Icon(Icons.person),
),
),
const SizedBox(height: 30),
ElevatedButton(
onPressed: isLoading ? null : login,
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(50),
backgroundColor: const Color(0xFF1565C0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child:
isLoading
? const CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(
Colors.white,
),
)
: const Text(
'تسجيل الدخول',
style: TextStyle(fontSize: 18),
),
),
if (message != null)
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text(
message!,
textAlign: TextAlign.center,
style: TextStyle(
color: isError ? Colors.red : Colors.green,
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 {
late Map<String, dynamic> currentUserData;
Timer? updateTimer;
bool isLoggingOut = false;
@override
void initState() {
super.initState();
currentUserData = widget.userData;
_startAutoUpdate();
}
void startAutoUpdate() {
updateTimer = Timer.periodic(const Duration(seconds: 5), () {
_fetchUserData();
});
}
Future fetchUserData() async {
try {
final res = await http
.get(Uri.parse('http://172.16.0.1/login?var=json'))
.timeout(const Duration(seconds: 10));
if (res.statusCode == 200) {
final data = json.decode(res.body);
if (!mounted) return;
if (!data.containsKey('errors')) {
setState(() {
currentUserData = data;
});
}
}
} catch () {
// تجاهل الأخطاء
}
}
Future _logout() async {
setState(() => isLoggingOut = true);
try {
final res = 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 (res.statusCode == 200 && 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'), backgroundColor: Colors.red),
);
}
} finally {
if (mounted) {
setState(() => isLoggingOut = false);
}
}
}
String _formatBytes(dynamic bytes) {
int value = 0;
if (bytes is String) {
value = int.tryParse(bytes) ?? 0;
} else if (bytes is int) {
value = bytes;
}
if (value < 1024) return 'valueبايت′;if(value<1024∗{(value / 1024).toStringAsFixed(1)} كيلوبايت';
if (value < 1024 * 1024 * 1024)
return '{(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت';
}
String _formatUptime(String uptime) {
if (uptime.endsWith('s')) {
final seconds = int.tryParse(uptime.replaceAll('s', '')) ?? 0;
if (seconds < 60) return 'seconds ثانية';
if (seconds < 3600) {
return '{(seconds / 60).floor()} دقيقة secondsreturn′{(seconds / 3600).floor()} ساعة ${(seconds % 3600 / 60).floor()} دقيقة';
}
return uptime;
}
String _decodeMac(String mac) {
return mac.replaceAll('%3A', ':');
}
@override
void dispose() {
updateTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final data = currentUserData;
final ip = data['ip'] ?? 'غير معروف';
final mac = _decodeMac(data['mac'] ?? 'غير معروف');
final bytesIn = _formatBytes(data['bytes_in'] ?? '0');
final bytesOut = _formatBytes(data['bytes_out'] ?? '0');
final uptime = _formatUptime(data['uptime'] ?? '0s');
final sessionTimeLeft = data['session_time_left'] ?? 'غير محدود';
return Scaffold(
appBar: AppBar(
title: const Text('لوحة التحكم'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _fetchUserData,
),
],
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
CircleAvatar(
radius: 30,
backgroundColor: Colors.blue[50],
child: const Icon(
Icons.person,
size: 30,
color: Colors.blue,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.username,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
const SizedBox(height: 4),
Text(
'مستخدم Hotspot',
style: TextStyle(color: Colors.grey[600]),
),
],
),
),
],
),
),
),
const SizedBox(height: 16),
_infoRow(Icons.computer, 'عنوان IP:', ip),
_infoRow(Icons.settings_ethernet, 'عنوان MAC:', mac),
const SizedBox(height: 16),
Expanded(
child: GridView.count(
crossAxisCount: 2,
childAspectRatio: 1.2,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
children: [
_statCard(Icons.timer, 'مدة الاتصال', uptime, Colors.blue),
_statCard(
Icons.download,
'البيانات المستلمة',
bytesIn,
Colors.purple,
),
_statCard(
Icons.upload,
'البيانات المرسلة',
bytesOut,
Colors.orange,
),
_statCard(
Icons.access_time,
'الوقت المتبقي',
sessionTimeLeft,
Colors.green,
),
],
),
),
const SizedBox(height: 16),
ElevatedButton.icon(
icon:
isLoggingOut
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: const Icon(Icons.logout),
label: Text(
isLoggingOut ? 'جاري تسجيل الخروج...' : 'تسجيل الخروج',
),
onPressed: isLoggingOut ? null : _logout,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red[400],
minimumSize: const Size.fromHeight(50),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
],
),
),
);
}
Widget _infoRow(IconData icon, String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
children: [
Icon(icon, size: 20, color: Colors.blue),
const SizedBox(width: 12),
Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(width: 8),
Expanded(
child: Text(
value,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.grey[700]),
),
),
],
),
);
}
Widget _statCard(IconData icon, String title, String value, Color color) {
return Card(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
backgroundColor: color.withOpacity(0.15),
child: Icon(icon, color: color),
),
const SizedBox(height: 12),
Text(
value,
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
textAlign: TextAlign.center,
),
const SizedBox(height: 4),
Text(
title,
style: TextStyle(color: Colors.grey[600], fontSize: 14),
textAlign: TextAlign.center,
),
],
),
),
);
}
}