صحح هذا الجزء في الكود await FlutterForegroundTask.init(… · The Chat Archive
Explore صحح هذا الجزء في الكود await FlutterForegroundTask.init( androidNotificationOptions:… Save Share Download ▾ Reportصحح هذا الجزء في الكود
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',
),
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: true,
playSound: false,
),
foregroundTaskOptions: const ForegroundTaskOptions(
autoRunOnBoot: false,
allowWakeLock: true,
allowWifiLock: true,
interval: 5000,
),
);
runApp(const MyApp());
}
للعلم الخطاء
This expression has a type of 'void' so its value can't be used.
Try checking to see if you're using the correct API; there might be a function or call that returns void y
و
The name 'NotificationIconData' isn't a class.
Try correcting the name to match an existing class.dartcreation_with_non_type
و
The named parameter 'eventAction' is required, but there's no corresponding argument.
Try adding the required argument.dartmissing_required_argument
و
The named parameter 'interval' isn't defined.
Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'interval'.dartundefined_named_parameter
والكود الكامل
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;
import 'package:flutter_foreground_task/models/notification_options.dart';
import 'package:flutter_foreground_task/models/notification_priority.dart';
import 'package:flutter_foreground_task/models/notification_channel_importance.dart';
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',
),
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: true,
playSound: false,
),
foregroundTaskOptions: const 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});
Assistant2025-05-25 08:36 UTC Copy response
ظهر هذا الخطاء
Target of URI doesn't exist: 'package:flutter_foreground_task/models/notification_importance.dart'.
Try creating the file referenced by the URI, or try using a URI for a file that does exist.darturi_does_not_exist
Assistant2025-05-25 08:38 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 2 (4 messages)
Language en
Conversation date May 25, 2025
Added to archive Nov 16, 2026
ID 01m7h42vn7mfx6g7sbav1wffjbSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: bf8cdecaf87b4d9e55c26696d810e1d2
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
@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();
});
}
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 '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 ( ) {
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, // تم التصحيح هنا
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,
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 '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 ( ) {
return bytes;
}
}
}
الرسائل التي تظهر في الكود تشير إلى عدة مشاكل في استخدام API مكتبة flutter_foreground_task وأسماء بعض الفئات (classes) والباراميترات (parameters).
سأقوم بشرح كل مشكلة مع كيفية تصحيحها وفقاً لأحدث إصدار مكتبة flutter_foreground_task:
1. مشكلة NotificationIconData غير موجودة كـ Class
الرسالة:
The name 'NotificationIconData' isn't a class.
في النسخ الحديثة من المكتبة، تم تغيير اسم أو طريقة تعريف الأيقونة . يجب عليك استخدام NotificationIcon بدلاً من NotificationIconData، كما يلي:
icon: const NotificationIcon(
resType: ResourceType.mipmap,
resPrefix: ResourcePrefix.ic,
name: 'launcher',
),
2. مشكلة الباراميتر eventAction المطلوب عند FlutterForegroundTask.init
الرسالة:
The named parameter 'eventAction' is required, but there's no corresponding argument.
في الإصدار الحالي من المكتبة، eventAction هو باراميتر إلزامي (required) في AndroidNotificationOptions ويجب عليك تمريره.
عادة هو EventAction.sendEvent أو قيمة من نوع EventAction.
إليك طريقة إضافته المحدثة:
androidNotificationOptions: AndroidNotificationOptions(
channelId: 'network_monitor_channel',
channelName: 'Network Monitor',
channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق',
channelImportance: NotificationImportance.DEFAULT,
priority: NotificationPriority.DEFAULT,
icon: const NotificationIcon(
resType: ResourceType.mipmap,
resPrefix: ResourcePrefix.ic,
name: 'launcher',
),
eventAction: EventAction.sendEvent, // هذا السطر هو المطلوب
),
3. خطأ interval غير معرف في ForegroundTaskOptions
الرسالة:
The named parameter 'interval' isn't defined.
في الإصدار الحالي تم إزالة باراميتر interval أو اسمه تغير.
حسب التوثيق الأحدث، interval يجب أن يكون ضمن ForegroundTaskNotificationOptions أو يتم تحديده داخل AndroidNotificationOptions أو يتم التعامل معه داخل إعدادات مهمة الـ foreground نفسها.
ولكن بشكل عام، في ForegroundTaskOptions الباراميترات المتاحة تشمل:
autoRunOnBoot
allowWakeLock
allowWifiLock
وليس interval.
لذا يجب إزالة السطر:
interval: 5000,
4. مشكلة تحذير:
This expression has a type of 'void' so its value can't be used.
هذه الرسالة بسبب محاولة استخدام القيمة المرجعة من دالة ترجع void بطريقة غير صحيحة، عادةً يكون في:
await FlutterForegroundTask.init( ... );
فقط تأكد أن init لا يعيد قيمة ويتم التعامل معها مباشرة (لا تحفظها في متغير).
الكود المعطى لا يبدو به هذه المشكلة واضحة، ولكن تأكد من عدم محاولة القيام بشيء مثل:
var initResult = await FlutterForegroundTask.init(...);
print(initResult); // لا تفعل هذا لأن init() ترجع void
التصحيح النهائي للجزء الخاص بـ init هو:
await FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: 'network_monitor_channel',
channelName: 'Network Monitor',
channelDescription: 'عرض حالة الشبكة عند الخروج من التطبيق',
channelImportance: NotificationImportance.DEFAULT,
priority: NotificationPriority.DEFAULT,
icon: const NotificationIcon(
resType: ResourceType.mipmap,
resPrefix: ResourcePrefix.ic,
name: 'launcher',
),
eventAction: EventAction.sendEvent, // باراميتر مطلوب
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: true,
playSound: false,
),
foregroundTaskOptions: const ForegroundTaskOptions(
autoRunOnBoot: false,
allowWakeLock: true,
allowWifiLock: true,
// إزالة baramter interval هنا لأنه غير معترف به
),
);
runApp(const MyApp());
أيضًا في مكان آخر في الكود
لاحظ في كود الـ WithForegroundTask في DashboardScreen, تم استخدام NotificationImportance و NotificationPriority، تأكد من الاستيراد الصحيح ومن الأسماء التالية:
import 'package:flutter_foreground_task/models/notification_priority.dart';
import 'package:flutter_foreground_task/models/notification_importance.dart'; // قد تكون "notification_channel_importance.dart" حسب الاصدار
ويجب استخدام:
channelImportance: NotificationImportance.DEFAULT,
priority: NotificationPriority.DEFAULT,
icon: const NotificationIcon(
resType: ResourceType.mipmap,
resPrefix: ResourcePrefix.ic,
name: 'launcher',
),
eventAction: EventAction.sendEvent,
ملخص النقاط الواجب تعديلها في كودك:
الخطأ التصحيح NotificationIconData غير موجوداستبداله بـ NotificationIcon eventAction مفقودإضافة eventAction: EventAction.sendEvent باراميتر interval في ForegroundTaskOptions إزالته لأنه غير مدعوَم استخدام NotificationChannelImportance استبداله بـ NotificationImportance
إذا كنت تستخدم نسخة محددة من المكتبة، تأكد من قراءة التوثيق الرسمي لـ flutter_foreground_task على pub.dev وطبق التعديلات حسب الإصدار لديك.
مثال كامل للتهيئة المصححة:
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,
priority: NotificationPriority.DEFAULT,
icon: const NotificationIcon(
resType: ResourceType.mipmap,
resPrefix: ResourcePrefix.ic,
name: 'launcher',
),
eventAction: EventAction.sendEvent,
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: true,
playSound: false,
),
foregroundTaskOptions: const ForegroundTaskOptions(
autoRunOnBoot: false,
allowWakeLock: true,
allowWifiLock: true,
),
);
runApp(const MyApp());
}
يرجى تجربة التعديلات وإعلامي في حال باقي هناك أي مشاكل أخرى أو رسائل خطأ.
الخطأ "Target of URI doesn't exist: 'package:flutter_foreground_task/models/notification_importance.dart'" يعني أن الملف أو الوحدة التي تحاول استيرادها غير موجودة في مكتبة flutter_foreground_task التي لديك.
السبب:
في النسخ الحديثة من مكتبة flutter_foreground_task، ظهرت تغييرات على أسماء ملفات الاستيراد (import paths) أو أن بعض الملفات أصبحت غير ضرورية للاستيراد يدويًا.
أو أن NotificationImportance الآن موجودة في ملف آخر، أو يتم استيرادها مباشرة من المسار الأساسي للمكتبة.
كيف تصلح المشكلة
1. حذف الاستيراد الخاطئ
قم بحذف السطر التالي:
import 'package:flutter_foreground_task/models/notification_importance.dart';
2. استخدم الاستيراد الأساسي فقط
غالباً يمكنك استخدام الاستيراد الأساسي للمكتبة flutter_foreground_task فقط، والذي يشمل كل ما تحتاجه:
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
هذا غالباً يحتوي على كل الكلاسات والأنواع مثل NotificationImportance وNotificationPriority.
توضيح:
NotificationImportance هو enum ضمن مكتبة flutter_foreground_task، ولا يلزم استيراد خاص له.
تأكد أنك تستخدم فقط:
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
ثم استخدم NotificationImportance.DEFAULT مباشرة.
مثال مبسط:
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, // هنا تستخدم مباشرة
priority: NotificationPriority.DEFAULT,
icon: const NotificationIcon(
resType: ResourceType.mipmap,
resPrefix: ResourcePrefix.ic,
name: 'launcher',
),
eventAction: EventAction.sendEvent,
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: true,
playSound: false,
),
foregroundTaskOptions: const ForegroundTaskOptions(
autoRunOnBoot: false,
allowWakeLock: true,
allowWifiLock: true,
),
);
runApp(const MyApp());
}
تأكد من إصدار المكتبة:
يمكنك التأكد من إصدار المكتبة الحالية لديك من خلال pubspec.yaml:
dependencies:
flutter_foreground_task: ^4.1.0 # أو الإصدار الذي تستخدمه
ثم نفذ في الطرفية:
flutter pub get
إذا استمرت المشكلات، أخبرني بالنسخة الحالية من مكتبة flutter_foreground_task لديك، وسأعطيك التعديلات الدقيقة بناءً عليها.
Copy first response
Not yet included in a published release.
(
1
)
ميجاباي
ت ′
;
r
e
t
u
r
n ′
(
1
)
ميجاباي
ت ′
;
r
e
t
u
r
n ′