بالطبع، لقد قمت بتحسين شكل الأزرار عن طريق تحديث ألوان الخلفية، إضافة الظلال (shadows)، وتحسين الحواف لجعل الشكل أكثر جمالًا وحداثة. أيضًا تمت إضافة أيقونات مناسبة إلى الأزرار المهمة وكذلك في أماكن تعديل المبالغ وإدارة الأرقام بما يتناسب مع وظيفة كل زر.
الكود التالي هو النسخة الكاملة بعد تطبيق التحسينات المطلوبة على الأزرار مع إضافة الأيقونات الملائمة:
// main.dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:telephony/telephony.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:url_launcher/url_launcher.dart';
// مكتبة الاتصال التلقائي
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
// استيراد شاشة الترحيب المنفصلة
import 'welcome_screen.dart';
void main() => runApp(const SMSApp());
void onBackgroundMessage(SmsMessage message) {
debugPrint("رسالة واردة في الخلفية: ${message.body}");
}
/// ألوان التطبيق المحدثة إلى أزرق جذاب
final ColorScheme lightColorScheme = ColorScheme(
primary: Color(0xFF1976D2),
onPrimary: Colors.white,
primaryContainer: Color(0xFFBBDEFB),
onPrimaryContainer: Color(0xFF0D47A1),
secondary: Color(0xFF0288D1),
onSecondary: Colors.white,
secondaryContainer: Color(0xFFB3E5FC),
onSecondaryContainer: Color(0xFF01579B),
tertiary: Color(0xFF64B5F6),
onTertiary: Colors.white,
tertiaryContainer: Color(0xFFBBDEFB),
onTertiaryContainer: Color(0xFF0D47A1),
error: Color(0xFFB00020),
onError: Colors.white,
errorContainer: Color(0xFFFFDAD6),
onErrorContainer: Color(0xFF410002),
background: Colors.white,
onBackground: Colors.black87,
surface: Colors.white,
onSurface: Colors.black87,
surfaceVariant: Color(0xFFE3F2FD),
onSurfaceVariant: Color(0xFF90CAF9),
outline: Color(0xFF90CAF9),
shadow: Colors.black54,
inverseSurface: Color(0xFF121212),
onInverseSurface: Colors.white,
inversePrimary: Color(0xFF82B1FF),
brightness: Brightness.light,
);
class SMSApp extends StatelessWidget {
const SMSApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'تحويل رصيد متعدد',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: lightColorScheme,
fontFamily: 'Tajawal',
useMaterial3: true,
appBarTheme: AppBarTheme(
backgroundColor: Colors.transparent,
foregroundColor: lightColorScheme.onPrimary,
elevation: 0,
centerTitle: true,
titleTextStyle: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
letterSpacing: 0.5,
),
iconTheme: IconThemeData(color: lightColorScheme.onPrimary, size: 26),
toolbarHeight: 80,
),
cardTheme: CardTheme(
color: lightColorScheme.surface,
elevation: 1,
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
surfaceTintColor: Colors.transparent,
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: lightColorScheme.primary,
foregroundColor: lightColorScheme.onPrimary,
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
elevation: 5,
shadowColor: lightColorScheme.primary.withOpacity(0.4),
textStyle: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w700,
),
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
foregroundColor: lightColorScheme.primary,
side: BorderSide(color: lightColorScheme.primary, width: 2),
padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 26),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
textStyle: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
),
),
),
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: lightColorScheme.primary,
textStyle: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 16,
),
),
),
snackBarTheme: SnackBarThemeData(
behavior: SnackBarBehavior.floating,
backgroundColor: lightColorScheme.inverseSurface,
elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
contentTextStyle: TextStyle(
color: lightColorScheme.onInverseSurface,
fontWeight: FontWeight.w500,
fontSize: 14,
),
actionTextColor: lightColorScheme.primaryContainer,
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: lightColorScheme.surfaceVariant.withOpacity(0.4),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 14,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide.none,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide(color: lightColorScheme.primary, width: 2),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide(color: lightColorScheme.error, width: 2),
),
labelStyle: TextStyle(
color: lightColorScheme.onSurfaceVariant,
fontWeight: FontWeight.w600,
),
hintStyle: TextStyle(
color: lightColorScheme.onSurfaceVariant.withOpacity(0.7),
),
prefixIconColor: lightColorScheme.primary,
),
dialogTheme: DialogTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
elevation: 6,
backgroundColor: lightColorScheme.surface,
contentTextStyle: TextStyle(
color: lightColorScheme.onSurface,
fontSize: 15,
),
titleTextStyle: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: lightColorScheme.onSurface,
),
),
listTileTheme: ListTileThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
contentPadding: const EdgeInsets.symmetric(horizontal: 18),
iconColor: lightColorScheme.primary,
textColor: lightColorScheme.onSurface,
dense: true,
),
chipTheme: ChipThemeData(
backgroundColor: lightColorScheme.surfaceVariant,
selectedColor: lightColorScheme.primary,
secondarySelectedColor: lightColorScheme.primary,
disabledColor: lightColorScheme.surfaceVariant.withOpacity(0.4),
labelStyle: const TextStyle(fontWeight: FontWeight.w600),
secondaryLabelStyle: TextStyle(color: lightColorScheme.onPrimary),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
brightness: Brightness.light,
side: BorderSide.none,
),
dividerTheme: DividerThemeData(
color: lightColorScheme.surfaceVariant,
thickness: 1,
space: 0,
),
progressIndicatorTheme: ProgressIndicatorThemeData(
color: lightColorScheme.primary,
linearTrackColor: lightColorScheme.surfaceVariant,
),
bottomSheetTheme: BottomSheetThemeData(
backgroundColor: lightColorScheme.surface,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
),
elevation: 8,
),
),
home: const SplashScreen(),
routes: {'/home': (context) => const SMSHomePage()},
);
}
}
class ThousandsSeparatorInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
String onlyDigits = newValue.text.replaceAll(RegExp(r'[^0-9]'), '');
if (onlyDigits.isEmpty) return newValue.copyWith(text: '');
final buffer = StringBuffer();
int len = onlyDigits.length;
for (int i = 0; i < len; i++) {
buffer.write(onlyDigits[i]);
int posFromRight = len - i - 1;
if (posFromRight % 3 == 0 && i != len - 1) buffer.write(',');
}
return TextEditingValue(
text: buffer.toString(),
selection: TextSelection.collapsed(offset: buffer.length),
);
}
}
class TransferItem {
String number;
int amount;
String? pin;
TransferItem({required this.number, required this.amount, this.pin});
Map<String, dynamic> toMap() {
return {'number': number, 'amount': amount, 'pin': pin};
}
factory TransferItem.fromMap(Map<String, dynamic> map) {
return TransferItem(
number: map['number'],
amount: map['amount'],
pin: map['pin'],
);
}
}
extension ContactExtensions on Contact {
String initials() {
if (displayName.isEmpty) return '';
final parts = displayName.trim().split(RegExp(r'\s+'));
if (parts.length == 1) {
return parts[0].substring(0, 1).toUpperCase();
} else {
return (parts[0].substring(0, 1) + parts[1].substring(0, 1))
.toUpperCase();
}
}
}
class NumberAmount {
String number;
String? displayName;
int amount;
NumberAmount({required this.number, this.displayName, required this.amount});
}
class SMSHomePage extends StatefulWidget {
const SMSHomePage({super.key});
@override
_SMSHomePageState createState() => _SMSHomePageState();
}
class _SMSHomePageState extends State<SMSHomePage>
with WidgetsBindingObserver, TickerProviderStateMixin {
final Telephony _telephony = Telephony.instance;
SharedPreferences? _prefs;
List<TransferItem> _transferList = [];
String _selectedMethod = 'yemenMobile';
bool _isTransferring = false;
bool _stopTransferRequested = false;
List<Map<String, dynamic>> _transferLogs = [];
List<String> _savedNumbers = [];
List<int> _savedAmounts = [];
bool _didShowFavoritesDialog = false;
String? _selectedQuickNumber;
int _currentBalance = 0;
late AnimationController _fabAnimationController;
late Animation<double> _fabAnimation;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_initApp();
_fabAnimationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
_fabAnimation = CurvedAnimation(
parent: _fabAnimationController,
curve: Curves.easeInOutBack,
);
// لضمان ظهور زر التحويل دائماً
_fabAnimationController.value = 1;
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_fabAnimationController.dispose();
super.dispose();
}
Future<void> _initApp() async {
_prefs = await SharedPreferences.getInstance();
_currentBalance = _prefs?.getInt('current_balance') ?? 0;
List<String>? amountsStr = _prefs?.getStringList('savedAmounts');
if (amountsStr != null) {
_savedAmounts =
amountsStr
.map((e) => int.tryParse(e) ?? 0)
.where((e) => e > 0)
.toList();
}
if (_savedAmounts.isEmpty && !_didShowFavoritesDialog) {
_didShowFavoritesDialog = true;
await Future.delayed(Duration.zero);
await _showFavoritesDialog();
}
List<String>? savedTransfers = _prefs?.getStringList('transferList');
if (savedTransfers != null && savedTransfers.isNotEmpty) {
_transferList =
savedTransfers
.map(
(e) => TransferItem.fromMap(
json.decode(e) as Map<String, dynamic>,
),
)
.toList();
} else {
_transferList = [];
}
_selectedMethod = _prefs?.getString('selectedMethod') ?? 'yemenMobile';
_savedNumbers = _prefs?.getStringList('savedNumbers') ?? [];
await _requestPermissions();
if (mounted) setState(() {});
}
Future<bool> _requestPermissions() async {
final phoneStatus = await Permission.phone.status;
final contactsStatus = await Permission.contacts.status;
if (!phoneStatus.isGranted || !contactsStatus.isGranted) {
final status = await [Permission.phone, Permission.contacts].request();
if (!status[Permission.phone]!.isGranted ||
!status[Permission.contacts]!.isGranted) {
_showSnackBar(
'يجب منح أذونات المكالمات وجهات الاتصال لاستخدام التطبيق',
);
return false;
}
}
return true;
}
Future<void> _saveTransferList() async {
final list = _transferList.map((e) => json.encode(e.toMap())).toList();
await _prefs?.setStringList('transferList', list);
}
Future<void> _saveSelectedMethod() async {
await _prefs?.setString('selectedMethod', _selectedMethod);
}
Future<void> _saveSavedNumbers() async {
await _prefs?.setStringList('savedNumbers', _savedNumbers);
}
Future<void> _saveSavedAmounts() async {
List<String> strList = _savedAmounts.map((e) => e.toString()).toList();
await _prefs?.setStringList('savedAmounts', strList);
}
Future<void> _saveCurrentBalance() async {
await _prefs?.setInt('current_balance', _currentBalance);
}
void _showSnackBar(String msg) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(msg, style: const TextStyle(fontWeight: FontWeight.w600)),
behavior: SnackBarBehavior.floating,
),
);
}
Future<String?> _getContactNameFromNumber(String number) async {
final hasPermission = await Permission.contacts.status;
if (!hasPermission.isGranted) {
final status = await Permission.contacts.request();
if (!status.isGranted) return null;
}
final contacts = await FlutterContacts.getContacts(withProperties: true);
for (var contact in contacts) {
for (var phone in contact.phones) {
final normalizedPhone = phone.number.replaceAll(RegExp(r'[^\d+]'), '');
final normalizedNumber = number.replaceAll(RegExp(r'[^\d+]'), '');
if (normalizedPhone == normalizedNumber) {
return contact.displayName;
}
}
}
return null;
}
Future<void> _showFavoritesDialog() async {
final amountsController = TextEditingController();
await showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: const Text('إعداد المبالغ المفضلة'),
content: StatefulBuilder(
builder: (context, setDialogState) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_savedAmounts.isEmpty)
Text(
'الرجاء إدخال المبالغ التي ترغب باستخدامها لاختيارها عند إضافة جهة اتصال',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
if (_savedAmounts.isNotEmpty)
Wrap(
spacing: 8,
runSpacing: 6,
children:
_savedAmounts
.map(
(amt) => Chip(
label: Text(
_formatWithThousandsSeparator(amt),
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
onDeleted: () {
setDialogState(() {
_savedAmounts.remove(amt);
});
},
deleteIconColor:
Theme.of(context).colorScheme.error,
),
)
.toList(),
),
const SizedBox(height: 16),
TextField(
controller: amountsController,
keyboardType: TextInputType.number,
inputFormatters: [ThousandsSeparatorInputFormatter()],
decoration: InputDecoration(
labelText: 'إضافة مبلغ جديد',
prefixIcon: const Icon(Icons.add_circle_outline_rounded),
suffixIcon: IconButton(
icon: const Icon(Icons.add_circle_rounded),
tooltip: 'إضافة المبلغ',
onPressed: () {
final raw = amountsController.text.replaceAll(
',',
'',
);
final numAmount = int.tryParse(raw);
if (numAmount == null || numAmount <= 0) {
_showSnackBar('يرجى إدخال مبلغ صحيح أكبر من صفر');
return;
}
if (_savedAmounts.contains(numAmount)) {
_showSnackBar('هذا المبلغ موجود بالفعل');
return;
}
setDialogState(() {
_savedAmounts.add(numAmount);
_savedAmounts.sort();
amountsController.clear();
});
},
),
),
onSubmitted: (value) {
final raw = value.replaceAll(',', '');
final numAmount = int.tryParse(raw);
if (numAmount == null || numAmount <= 0) {
_showSnackBar('يرجى إدخال مبلغ صحيح أكبر من صفر');
return;
}
if (_savedAmounts.contains(numAmount)) {
_showSnackBar('هذا المبلغ موجود بالفعل');
return;
}
setDialogState(() {
_savedAmounts.add(numAmount);
_savedAmounts.sort();
amountsController.clear();
});
},
),
],
);
},
),
actions: [
TextButton.icon(
icon: const Icon(Icons.skip_next_rounded),
onPressed: () => Navigator.pop(context),
label: const Text('تخطي'),
),
FilledButton.icon(
icon: const Icon(Icons.save_rounded),
onPressed: () async {
if (_savedAmounts.isEmpty) {
_showSnackBar('الرجاء إدخال مبلغ واحد على الأقل');
return;
}
await _saveSavedAmounts();
Navigator.pop(context);
},
label: const Text('حفظ'),
),
],
);
},
);
}
Future<int?> _pickAmountDialog() async {
if (_savedAmounts.isEmpty) {
_showSnackBar('لا توجد مبالغ محفوظة. الرجاء إضافتها في الإعدادات.');
return null;
}
int? selectedAmount;
await showModalBottomSheet(
context: context,
builder: (context) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Wrap(
spacing: 12,
children:
_savedAmounts
.map(
(amount) => ChoiceChip(
label: Text(
_formatWithThousandsSeparator(amount),
style: TextStyle(
fontWeight: FontWeight.w700,
color:
selectedAmount == amount
? Theme.of(context).colorScheme.onPrimary
: Theme.of(context).colorScheme.primary,
),
),
selected: selectedAmount == amount,
onSelected: (_) {
selectedAmount = amount;
Navigator.pop(context);
},
),
)
.toList(),
),
),
);
},
);
return selectedAmount;
}
void _showSavedNumbersSelection() async {
final hasPermission = await _requestPermissions();
if (!hasPermission) return;
final contacts = await FlutterContacts.getContacts(
withProperties: true,
withThumbnail: true,
);
List<String> selectedNumbers = List.from(_savedNumbers);
TextEditingController searchController = TextEditingController();
String searchQuery = '';
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) {
return StatefulBuilder(
builder: (context, setModal) {
final filteredContacts =
searchQuery.isEmpty
? contacts
: contacts.where((contact) {
final contactNameLower =
contact.displayName.toLowerCase();
final queryLower = searchQuery.toLowerCase();
final phonesMatch = contact.phones.any(
(phone) =>
phone.number.toLowerCase().contains(queryLower),
);
return contactNameLower.contains(queryLower) ||
phonesMatch;
}).toList();
return Container(
height: MediaQuery.of(context).size.height * 0.85,
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
child: Row(
children: [
Expanded(
child: TextField(
controller: searchController,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search_rounded),
hintText: 'ابحث في جهات الاتصال أو الأرقام',
isDense: true,
),
onChanged: (value) {
setModal(() {
searchQuery = value.trim();
});
},
),
),
const SizedBox(width: 8),
IconButton(
icon: const Icon(Icons.close_rounded),
tooltip: 'إغلاق',
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(height: 1),
Expanded(
child:
filteredContacts.isEmpty
? Center(
child: Text(
'لا توجد جهات اتصال تطابق البحث',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(
color:
Theme.of(
context,
).colorScheme.onSurfaceVariant,
),
),
)
: ListView.builder(
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
physics: const BouncingScrollPhysics(),
itemCount: filteredContacts.length,
itemBuilder: (context, index) {
final contact = filteredContacts[index];
final phones = contact.phones;
return Card(
margin: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 8,
horizontal: 12,
),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
ListTile(
contentPadding: EdgeInsets.zero,
leading: CircleAvatar(
radius: 24,
backgroundImage:
(contact.thumbnail != null &&
contact
.thumbnail!
.isNotEmpty)
? MemoryImage(
contact.thumbnail!,
)
: null,
child:
(contact.thumbnail == null ||
contact
.thumbnail!
.isEmpty)
? Text(
contact.initials(),
style: const TextStyle(
fontWeight:
FontWeight.bold,
color: Colors.white,
fontSize: 18,
),
)
: null,
backgroundColor:
Theme.of(
context,
).colorScheme.primary,
),
title: Text(
contact.displayName,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(height: 4),
Column(
children:
phones.map((phone) {
final normalized = phone.number
.replaceAll(
RegExp(r'[^\d+]'),
'',
);
final isSelected =
selectedNumbers.any((num) {
final n = num.replaceAll(
RegExp(r'[^\d+]'),
'',
);
return n == normalized;
});
return CheckboxListTile(
contentPadding:
EdgeInsets.zero,
value: isSelected,
title: Text(
phone.number,
style: const TextStyle(
fontSize: 14,
fontWeight:
FontWeight.w600,
),
),
controlAffinity:
ListTileControlAffinity
.leading,
onChanged: (val) {
setModal(() {
if (val == true) {
if (!selectedNumbers.any(
(num) {
final n =
num.replaceAll(
RegExp(
r'[^\d+]',
),
'',
);
return n ==
normalized;
},
)) {
selectedNumbers.add(
phone.number,
);
}
} else {
selectedNumbers
.removeWhere((num) {
final n =
num.replaceAll(
RegExp(
r'[^\d+]',
),
'',
);
return n ==
normalized;
});
}
});
},
);
}).toList(),
),
],
),
),
);
},
),
),
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Expanded(
child: OutlinedButton.icon(
icon: const Icon(Icons.cancel_rounded),
onPressed: () => Navigator.pop(context),
label: const Text('إلغاء'),
style: OutlinedButton.styleFrom(
side: BorderSide(
color: Theme.of(context).colorScheme.primary,
),
),
),
),
const SizedBox(width: 12),
Expanded(
child: FilledButton.icon(
icon: const Icon(Icons.save_rounded),
onPressed: () async {
_savedNumbers = List.from(selectedNumbers);
await _saveSavedNumbers();
Navigator.pop(context);
_showSnackBar('تم حفظ الأرقام المختارة');
if (mounted) setState(() {});
},
label: const Text('حفظ'),
),
),
],
),
),
],
),
);
},
);
},
);
}
Future<void> _showBatchAmountAssignmentDialog(List<String> numbers) async {
if (numbers.isEmpty) {
_showSnackBar('لا توجد أرقام لتحديثها');
return;
}
if (_savedAmounts.isEmpty) {
_showSnackBar('لا توجد مبالغ محفوظة. الرجاء إضافتها في الإعدادات.');
return;
}
List<NumberAmount> tempList = [];
for (var number in numbers) {
String? name = await _getContactNameFromNumber(number);
final existing = _transferList.firstWhere(
(element) => element.number == number,
orElse: () => TransferItem(number: number, amount: 0),
);
tempList.add(
NumberAmount(
number: number,
displayName: name,
amount: existing.amount > 0 ? existing.amount : 0,
),
);
}
final formKey = GlobalKey<FormState>();
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('تعيين مبلغ لكل رقم'),
content: StatefulBuilder(
builder: (context, setDialogState) {
return Form(
key: formKey,
child: SizedBox(
width: double.maxFinite,
child: ListView.separated(
shrinkWrap: true,
physics: const ClampingScrollPhysics(),
separatorBuilder: (_, __) => const SizedBox(height: 16),
itemCount: tempList.length,
itemBuilder: (context, index) {
final item = tempList[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.displayName ?? item.number,
style: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 16,
),
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 8),
DropdownButtonFormField<int>(
decoration: const InputDecoration(
labelText: 'المبلغ',
isDense: true,
),
items:
_savedAmounts
.map(
(e) => DropdownMenuItem(
value: e,
child: Text(
_formatWithThousandsSeparator(e),
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
),
)
.toList(),
value: item.amount > 0 ? item.amount : null,
onChanged: (val) {
setDialogState(() {
item.amount = val ?? 0;
});
},
validator: (val) {
if (val == null || val <= 0) {
return 'يرجى اختيار مبلغ صالح';
}
return null;
},
isExpanded: true,
),
],
);
},
),
),
);
},
),
actions: [
TextButton.icon(
icon: const Icon(Icons.cancel_rounded),
onPressed: () => Navigator.pop(context),
label: const Text('إلغاء'),
),
FilledButton.icon(
icon: const Icon(Icons.save_rounded),
onPressed: () async {
if (!formKey.currentState!.validate()) {
_showSnackBar('يرجى إدخال جميع المبالغ بشكل صحيح');
return;
}
for (var item in tempList) {
if (!_transferList.any((e) => e.number == item.number)) {
_transferList.add(
TransferItem(
number: item.number,
amount: item.amount,
pin:
(_selectedMethod == 'yemenMobile' ||
_selectedMethod == 'sabafon')
? '1234'
: null,
),
);
} else {
final existingIndex = _transferList.indexWhere(
(e) => e.number == item.number,
);
if (existingIndex != -1) {
_transferList[existingIndex].amount = item.amount;
if (_selectedMethod == 'yemenMobile' ||
_selectedMethod == 'sabafon') {
_transferList[existingIndex].pin ??= '1234';
} else {
_transferList[existingIndex].pin = null;
}
}
}
}
await _saveTransferList();
setState(() {});
Navigator.pop(context);
_showSnackBar('تم تحديث قائمة التحويل بالمبالغ المحددة');
},
label: const Text('حفظ'),
),
],
);
},
);
}
String _formatWithThousandsSeparator(int value) {
final s = value.toString();
final buffer = StringBuffer();
int len = s.length;
for (int i = 0; i < len; i++) {
buffer.write(s[i]);
int posFromRight = len - i - 1;
if (posFromRight % 3 == 0 && i != len - 1) {
buffer.write(',');
}
}
return buffer.toString();
}
// **التعديل الرئيسي: استخدام flutter_phone_direct_caller للاتصال التلقائي**
Future<void> _startTransferSequence() async {
if (_transferList.isEmpty) {
_showSnackBar("لا توجد معاملات للتحويل");
return;
}
int totalAmount = _transferList.fold(0, (sum, item) => sum + item.amount);
if (totalAmount > _currentBalance) {
_showSnackBar(
"الرصيد الحالي (${_formatWithThousandsSeparator(_currentBalance)}) غير كافٍ لإجراء التحويلات (المجموع: ${_formatWithThousandsSeparator(totalAmount)})",
);
return;
}
// طلب إذن الاتصال CALL_PHONE
if (!await Permission.phone.isGranted) {
final status = await Permission.phone.request();
if (!status.isGranted) {
_showSnackBar("يجب منح إذن الاتصال لإجراء تحويل الرصيد");
return;
}
}
final phonePermissionStatus = await Permission.phone.status;
if (!phonePermissionStatus.isGranted) {
final status = await Permission.phone.request();
if (!status.isGranted) {
_showSnackBar("يجب منح إذن الاتصال لإجراء تحويل الرصيد");
return;
}
}
setState(() {
_isTransferring = true;
_stopTransferRequested = false;
});
_fabAnimationController.forward();
_transferLogs.clear();
List<TransferItem> tempTransferList = List.from(_transferList);
List<String> successfullyTransferredNumbers = [];
for (var i = 0; i < tempTransferList.length; i++) {
if (_stopTransferRequested) {
_showSnackBar("تم إيقاف عملية التحويل");
break;
}
var item = tempTransferList[i];
String ussdCode = _buildUssdCode(item);
_showSnackBar(
'جاري تحويل ${_getMethodName(_selectedMethod)}: ${_formatWithThousandsSeparator(item.amount)} إلى ${item.number} (${i + 1}/${tempTransferList.length})',
);
try {
bool? called = await FlutterPhoneDirectCaller.callNumber(ussdCode);
if (called == true) {
_transferLogs.add({
'number': item.number,
'amount': item.amount,
'success': true,
'method': _selectedMethod,
});
successfullyTransferredNumbers.add(item.number);
setState(() {
_currentBalance -= item.amount;
});
await _saveCurrentBalance();
await Future.delayed(const Duration(seconds: 10));
} else {
_transferLogs.add({
'number': item.number,
'amount': item.amount,
'success': false,
'method': _selectedMethod,
'error': 'فشل في إجراء الاتصال التلقائي',
});
}
} catch (e) {
_transferLogs.add({
'number': item.number,
'amount': item.amount,
'success': false,
'method': _selectedMethod,
'error': e.toString(),
});
}
}
setState(() {
for (var number in successfullyTransferredNumbers) {
_transferList.removeWhere((t) => t.number == number);
_savedNumbers.removeWhere(
(num) => _normalizeNumber(num) == _normalizeNumber(number),
);
if (_selectedQuickNumber == number) _selectedQuickNumber = null;
}
});
await _saveTransferList();
await _saveSavedNumbers();
setState(() {
_isTransferring = false;
});
_fabAnimationController.reverse();
if (!_stopTransferRequested) {
_showSnackBar("تمت جميع عمليات التحويل");
}
}
String _normalizeNumber(String number) {
return number.replaceAll(RegExp(r'[^\d+]'), '');
}
String _getMethodName(String method) {
switch (method) {
case 'yemenMobile':
return 'يمن موبايل';
case 'y':
return 'واي';
case 'sabafon':
return 'سبأفون';
case 'you':
return 'يو';
default:
return method;
}
}
String _buildUssdCode(TransferItem item) {
final number = item.number;
final amount = item.amount.toString();
final pin = item.pin ?? '1234';
switch (_selectedMethod) {
case 'yemenMobile':
return '*888*$amount*$number*$pin#'.replaceAll(
'#',
Uri.encodeComponent('#'),
);
case 'y':
return '*109*$amount*$number#'.replaceAll(
'#',
Uri.encodeComponent('#'),
);
case 'sabafon':
return '*123*$pin*$number*$amount#'.replaceAll(
'#',
Uri.encodeComponent('#'),
);
case 'you':
return '*130*$number*$amount#'.replaceAll(
'#',
Uri.encodeComponent('#'),
);
default:
return '';
}
}
void _showTransferLogsDialog() {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('سجل عمليات التحويل'),
content: SizedBox(
width: double.maxFinite,
child:
_transferLogs.isEmpty
? Center(
child: Text(
'لا توجد عمليات تحويل حتى الآن',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
)
: ListView.builder(
shrinkWrap: true,
physics: const ClampingScrollPhysics(),
itemCount: _transferLogs.length,
itemBuilder: (_, i) {
final log = _transferLogs[i];
final success = log['success'] as bool;
return ListTile(
contentPadding: EdgeInsets.zero,
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color:
success
? Theme.of(
context,
).colorScheme.primaryContainer
: Theme.of(
context,
).colorScheme.errorContainer,
shape: BoxShape.circle,
),
child: Icon(
success ? Icons.check_circle_rounded : Icons.cancel_rounded,
color:
success
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.error,
size: 28,
),
),
title: Text(
'${_getMethodName(log['method'])} - ${log['number']}',
style: const TextStyle(fontWeight: FontWeight.w700),
),
subtitle: Text(
'المبلغ: ${_formatWithThousandsSeparator(log['amount'] ?? 0)}',
),
);
},
),
),
actions: [
TextButton.icon(
icon: const Icon(Icons.close_rounded),
onPressed: () => Navigator.pop(context),
label: const Text('إغلاق'),
),
],
);
},
);
}
void _showAmountsManagementDialog() async {
final amountsController = TextEditingController();
bool isValidInput(String value) {
final raw = value.replaceAll(',', '');
final numAmount = int.tryParse(raw);
return numAmount != null &&
numAmount > 0 &&
!_savedAmounts.contains(numAmount);
}
void addAmount(
String value,
void Function(void Function()) setDialogState,
) {
final raw = value.replaceAll(',', '');
final numAmount = int.tryParse(raw);
if (numAmount == null || numAmount <= 0) {
_showSnackBar('يرجى إدخال مبلغ صحيح أكبر من صفر');
return;
}
if (_savedAmounts.contains(numAmount)) {
_showSnackBar('هذا المبلغ موجود بالفعل');
return;
}
setDialogState(() {
_savedAmounts.add(numAmount);
_savedAmounts.sort();
amountsController.clear();
});
}
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text(
'إدارة المبالغ المحفوظة',
textAlign: TextAlign.center,
),
content: StatefulBuilder(
builder: (context, setDialogState) {
return SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_savedAmounts.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
'لا توجد مبالغ محفوظة حالياً',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(
color:
Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
if (_savedAmounts.isNotEmpty)
Container(
constraints: BoxConstraints(maxHeight: 160),
child: SingleChildScrollView(
child: Wrap(
spacing: 10,
runSpacing: 8,
children:
_savedAmounts
.map(
(amt) => Tooltip(
message: 'حذف هذا المبلغ',
child: Chip(
label: Text(
_formatWithThousandsSeparator(amt),
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
backgroundColor: Theme.of(context)
.colorScheme
.primaryContainer
.withOpacity(0.4),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
24,
),
),
onDeleted: () {
setDialogState(() {
_savedAmounts.remove(amt);
});
},
deleteIconColor:
Theme.of(
context,
).colorScheme.error,
),
),
)
.toList(),
),
),
),
const Divider(height: 25, thickness: 1),
TextField(
controller: amountsController,
keyboardType: TextInputType.number,
inputFormatters: [ThousandsSeparatorInputFormatter()],
decoration: InputDecoration(
labelText: 'إضافة مبلغ جديد',
prefixIcon: const Icon(Icons.add_circle_outline_rounded),
suffixIcon: IconButton(
icon: const Icon(Icons.add_circle_rounded),
tooltip: 'إضافة المبلغ',
onPressed:
isValidInput(amountsController.text)
? () => addAmount(
amountsController.text,
setDialogState,
)
: null,
),
),
onChanged: (value) {
setDialogState(() {}); // لتحديث زر الإضافة
},
onSubmitted: (value) {
addAmount(value, setDialogState);
},
),
],
),
);
},
),
actionsAlignment: MainAxisAlignment.spaceBetween,
actions: [
TextButton.icon(
icon: const Icon(Icons.close_rounded),
onPressed: () => Navigator.pop(context),
label: const Text('إغلاق'),
),
FilledButton.icon(
icon: const Icon(Icons.save_rounded),
onPressed: () async {
await _saveSavedAmounts();
Navigator.pop(context);
_showSnackBar('تم حفظ المبالغ بنجاح');
},
label: const Text('حفظ'),
),
],
);
},
);
}
void _stopTransferSequence() {
if (_isTransferring) {
setState(() {
_stopTransferRequested = true;
});
_showSnackBar("تم طلب إيقاف عملية التحويل");
}
}
Widget _buildCurrentTransferMethodSection() {
final methodNames = {
'yemenMobile': 'يمن موبايل',
'y': 'واي',
'sabafon': 'سبأفون',
'you': 'يو',
};
final methodIcons = {
'yemenMobile': Icons.sim_card_rounded,
'y': Icons.sim_card_rounded,
'sabafon': Icons.sim_card_rounded,
'you': Icons.sim_card_rounded,
};
final methodName = methodNames[_selectedMethod] ?? _selectedMethod;
final methodIcon = methodIcons[_selectedMethod] ?? Icons.sync;
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
elevation: 4,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
Icons.swap_horiz_rounded,
color: Theme.of(context).colorScheme.primary,
size: 28,
),
const SizedBox(width: 14),
Text(
'طريقة التحويل الحالية',
style: Theme.of(
context,
).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
),
],
),
const SizedBox(height: 18),
Row(
children: [
Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
blurRadius: 10,
offset: Offset(0, 3),
),
],
),
padding: const EdgeInsets.all(14),
child: Icon(
methodIcon,
size: 44,
color: Theme.of(context).colorScheme.primary,
),
),
const SizedBox(width: 20),
Expanded(
child: Text(
methodName,
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.primary,
),
),
),
FilledButton.icon(
icon: const Icon(Icons.edit_rounded),
onPressed: () async {
final selected = await showDialog<String>(
context: context,
builder: (context) {
return SimpleDialog(
title: const Text('اختر طريقة التحويل'),
children:
methodNames.entries.map((entry) {
final isSelected = entry.key == _selectedMethod;
return SimpleDialogOption(
onPressed:
() => Navigator.pop(context, entry.key),
child: Row(
children: [
Icon(
methodIcons[entry.key],
color:
isSelected
? Theme.of(
context,
).colorScheme.primary
: Theme.of(
context,
).colorScheme.onSurfaceVariant,
size: 24,
),
const SizedBox(width: 16),
Text(entry.value),
if (isSelected)
const Padding(
padding: EdgeInsets.only(left: 12),
child: Icon(Icons.check_circle_rounded, color: Colors.green),
),
],
),
);
}).toList(),
);
},
);
if (selected != null && selected != _selectedMethod) {
setState(() {
_selectedMethod = selected;
if (_selectedMethod == 'yemenMobile' ||
_selectedMethod == 'sabafon') {
for (var item in _transferList) {
item.pin ??= '1234';
}
} else {
for (var item in _transferList) {
item.pin = null;
}
}
_saveSelectedMethod();
});
_showSnackBar(
'تم تغيير طريقة التحويل إلى ${methodNames[selected]}',
);
}
},
label: const Text('تغيير'),
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 20,
),
textStyle: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
),
],
),
const SizedBox(height: 12),
Text(
'سيتم استخدام هذه الطريقة لأوامر USSD في عمليات تحويل الرصيد المتعددة.',
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
Widget fabChild = _isTransferring
? Row(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
color: Theme.of(context).colorScheme.onPrimary,
strokeWidth: 3,
),
),
const SizedBox(width: 12),
const Text(
'إيقاف التحويل',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17,
),
),
],
)
: Row(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.send_rounded, size: 24),
SizedBox(width: 10),
Text(
'إجراء التحويلات',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17,
),
),
],
);
return Scaffold(
appBar: AppBar(
toolbarHeight: 100,
title: Row(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(width: 16),
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'تحويل رصيد متعدد',
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.w900,
letterSpacing: 0.9),
),
Text(
'الرصيد: ${_formatWithThousandsSeparator(_currentBalance)}',
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w600, height: 1.4),
),
],
),
],
),
actions: [
Tooltip(
message: 'إدارة المبالغ المحفوظة',
child: CircleAvatar(
backgroundColor:
lightColorScheme.primaryContainer.withOpacity(0.8),
child: IconButton(
icon: const Icon(Icons.attach_money_rounded, color: Colors.white, size: 26),
onPressed: _showAmountsManagementDialog,
),
),
),
const SizedBox(width: 14),
Tooltip(
message: 'إدارة الأرقام المحفوظة',
child: CircleAvatar(
backgroundColor:
lightColorScheme.primaryContainer.withOpacity(0.8),
child: IconButton(
icon: const Icon(Icons.contact_page_rounded, color: Colors.white, size: 26),
onPressed: _showSavedNumbersSelection,
),
),
),
const SizedBox(width: 12),
],
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
lightColorScheme.primary,
lightColorScheme.primaryContainer,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: const BorderRadius.vertical(bottom: Radius.circular(24)),
),
),
elevation: 8,
shadowColor: lightColorScheme.primary.withOpacity(0.45),
),
floatingActionButton: ScaleTransition(
scale: _fabAnimation,
child: FloatingActionButton.extended(
onPressed:
_isTransferring ? _stopTransferSequence : _startTransferSequence,
icon: _isTransferring ? null : const Icon(Icons.send_rounded),
label: fabChild,
elevation: 8,
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Theme.of(context).colorScheme.onPrimary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
bottomNavigationBar:
(_transferLogs.isNotEmpty)
? SafeArea(
child: Padding(
padding: const EdgeInsets.all(18),
child: FilledButton.icon(
icon: const Icon(Icons.history_rounded),
label: const Text(
'عرض سجل التحويلات',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
elevation: 6,
backgroundColor: Theme.of(context).colorScheme.primary,
),
onPressed: _showTransferLogsDialog,
),
),
)
: null,
body: Column(
children: [
_buildCurrentTransferMethodSection(),
if (_savedNumbers.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'اختيار رقم سريع للتحويل',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
SizedBox(
height: 80,
child: FutureBuilder<List<Map<String, String?>>>(
future: Future.wait(
_savedNumbers.map((number) async {
final name = await _getContactNameFromNumber(number);
return {'number': number, 'name': name};
}).toList(),
),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
}
final data = snapshot.data!;
return ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: data.length,
separatorBuilder:
(_, __) => const SizedBox(width: 14),
itemBuilder: (context, index) {
final item = data[index];
final number = item['number']!;
final displayText =
item['name']?.isNotEmpty == true
? item['name']
: number;
final bool isSelected =
_selectedQuickNumber == number;
String initials = '';
if (item['name']?.isNotEmpty == true) {
final parts = displayText!.trim().split(' ');
if (parts.length == 1) {
initials = parts[0][0];
} else if (parts.length > 1) {
initials = parts[0][0] + parts[1][0];
}
} else {
initials = number.substring(0, 2);
}
initials = initials.toUpperCase();
return GestureDetector(
onTap: () {
setState(() {
if (isSelected) {
_selectedQuickNumber = null;
} else {
_selectedQuickNumber = number;
if (!_transferList.any(
(e) => e.number == number,
)) {
final defaultAmount =
_savedAmounts.isNotEmpty
? _savedAmounts.first
: 0;
_transferList.add(
TransferItem(
number: number,
amount: defaultAmount,
pin:
(_selectedMethod ==
'yemenMobile' ||
_selectedMethod ==
'sabafon')
? '1234'
: null,
),
);
_saveTransferList();
}
}
});
},
child: Container(
width: 150,
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 10,
),
decoration: BoxDecoration(
color:
isSelected
? Theme.of(
context,
).colorScheme.primary
: Theme.of(
context,
).colorScheme.surfaceVariant,
borderRadius: BorderRadius.circular(16),
boxShadow: isSelected
? [
BoxShadow(
color: Theme.of(context)
.colorScheme
.primary
.withOpacity(0.35),
blurRadius: 12,
offset: const Offset(0, 4),
)
]
: null,
),
child: Row(
children: [
CircleAvatar(
radius: 22,
backgroundColor:
isSelected
? Theme.of(
context,
).colorScheme.surface
: Theme.of(
context,
).colorScheme.primary,
child: Text(
initials,
style: TextStyle(
color:
isSelected
? Theme.of(
context,
).colorScheme.primary
: Theme.of(
context,
).colorScheme.onPrimary,
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
),
const SizedBox(width: 14),
Expanded(
child: Text(
displayText ?? number,
style: TextStyle(
color:
isSelected
? Theme.of(
context,
).colorScheme.onPrimary
: Theme.of(
context,
).colorScheme.onSurface,
fontWeight: FontWeight.w700,
fontSize: 14,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
);
},
);
},
),
),
// زر حذف جهة الاتصال المحددة يظهر فقط عند اختيار رقم سريع
if (_selectedQuickNumber != null)
Padding(
padding: const EdgeInsets.only(top: 14),
child: Align(
alignment: Alignment.centerRight,
child: OutlinedButton.icon(
icon: const Icon(Icons.delete_forever_rounded),
label: const Text(
'حذف الرقم المختار',
style: TextStyle(fontWeight: FontWeight.bold),
),
style: OutlinedButton.styleFrom(
foregroundColor:
Theme.of(context).colorScheme.error,
side: BorderSide(
color: Theme.of(context).colorScheme.error,
width: 2,
),
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 20,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
textStyle: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 16,
),
),
onPressed: () async {
final confirm = await showDialog<bool>(
context: context,
builder:
(context) => AlertDialog(
title: const Text('تأكيد الحذف'),
content: const Text(
'هل أنت متأكد من حذف الرقم المختار من الأرقام المحفوظة؟',
),
actions: [
TextButton(
onPressed:
() => Navigator.pop(context, false),
child: const Text('إلغاء'),
),
FilledButton(
onPressed:
() => Navigator.pop(context, true),
child: const Text('حذف'),
),
],
),
);
if (confirm == true) {
setState(() {
_savedNumbers.removeWhere(
(num) =>
_normalizeNumber(num) ==
_normalizeNumber(_selectedQuickNumber!),
);
_transferList.removeWhere(
(item) => item.number == _selectedQuickNumber,
);
_selectedQuickNumber = null;
});
await _saveSavedNumbers();
await _saveTransferList();
_showSnackBar('تم حذف الرقم من الأرقام المحفوظة');
}
},
),
),
),
],
),
),
const Divider(height: 1),
Expanded(
child: _transferList.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.phone_android_rounded,
size: 70,
color:
Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(height: 20),
Text(
'لا توجد عمليات تحويل',
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(
color:
Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 10),
Text(
'يمكنك إضافة الأرقام المفضلة لإجراء التحويلات بسهولة.',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(
color:
Theme.of(context).colorScheme.onSurfaceVariant,
),
textAlign: TextAlign.center,
),
],
),
)
: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: _transferList.length,
padding: const EdgeInsets.only(bottom: 80),
itemBuilder: (context, index) {
final item = _transferList[index];
return Dismissible(
key: Key('${item.number}_$index'),
background: Container(
margin: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
decoration: BoxDecoration(
color:
Theme.of(context).colorScheme.errorContainer,
borderRadius: BorderRadius.circular(16),
),
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: 28),
child: Icon(
Icons.delete_rounded,
color: Theme.of(context).colorScheme.error,
size: 28,
),
),
direction: DismissDirection.endToStart,
onDismissed: (direction) => _removeTransferAt(index),
child: Card(
margin: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
elevation: 3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
child: ListTile(
leading: Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color:
Theme.of(context).colorScheme.primaryContainer,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Theme.of(context)
.colorScheme
.primary
.withOpacity(0.3),
blurRadius: 6,
offset: const Offset(0, 2),
),
],
),
child: Icon(
Icons.phone_android_rounded,
color: Theme.of(context).colorScheme.primary,
size: 28,
),
),
title: Text(
item.number,
style: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 16,
),
),
subtitle: Text(
'المبلغ: ${_formatWithThousandsSeparator(item.amount)}',
style: const TextStyle(fontSize: 14),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Tooltip(
message: 'تعديل',
child: IconButton(
icon: Icon(
Icons.edit_rounded,
color:
Theme.of(context).colorScheme.primary,
size: 26,
),
onPressed: () => _editTransfer(index),
),
),
Tooltip(
message: 'حذف',
child: IconButton(
icon: Icon(
Icons.delete_forever_rounded,
color:
Theme.of(context).colorScheme.error,
size: 26,
),
onPressed: () => _removeTransferAt(index),
),
),
],
),
),
),
);
},
),
),
],
),
);
}
void _removeTransferAt(int index) async {
setState(() {
_transferList.removeAt(index);
});
await _saveTransferList();
}
void _editTransfer(int index) {
var item = _transferList[index];
int? selectedAmount = item.amount;
final pinController = TextEditingController(text: item.pin ?? '1234');
showModalBottomSheet(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(24))),
builder: (context) {
return StatefulBuilder(
builder: (context, setModal) {
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
top: 22,
left: 22,
right: 22,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Expanded(
child: Text(
"تعديل التحويل",
style: Theme.of(context).textTheme.headlineSmall
?.copyWith(fontWeight: FontWeight.bold),
),
),
IconButton(
icon: const Icon(Icons.close_rounded),
tooltip: 'إغلاق',
onPressed: () => Navigator.pop(context),
),
],
),
const SizedBox(height: 8),
Text(
item.number,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w600,
fontSize: 15,
),
),
const Divider(height: 28),
Align(
alignment: Alignment.centerRight,
child: Text(
'اختر المبلغ',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(height: 14),
Wrap(
spacing: 12,
children: _savedAmounts
.map(
(amt) => ChoiceChip(
label: Text(
_formatWithThousandsSeparator(amt),
style: TextStyle(
fontWeight: FontWeight.w700,
color: selectedAmount == amt
? Theme.of(context).colorScheme.onPrimary
: Theme.of(context).colorScheme.primary,
),
),
selected: selectedAmount == amt,
selectedColor: Theme.of(context).colorScheme.primary,
onSelected: (_) {
setModal(() {
selectedAmount = amt;
});
},
),
)
.toList(),
),
if (_selectedMethod == 'yemenMobile' ||
_selectedMethod == 'sabafon')
Padding(
padding: const EdgeInsets.fromLTRB(0, 26, 0, 18),
child: TextField(
controller: pinController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: "الرقم السري",
prefixIcon: const Icon(Icons.lock_outline_rounded),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
),
obscureText: true,
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
const SizedBox(height: 18),
Row(
children: [
Expanded(
child: OutlinedButton.icon(
icon: const Icon(Icons.cancel_rounded),
label: const Text("إلغاء"),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
textStyle: const TextStyle(
fontWeight: FontWeight.w700, fontSize: 16),
),
onPressed: () => Navigator.pop(context),
),
),
const SizedBox(width: 14),
Expanded(
child: FilledButton.icon(
icon: const Icon(Icons.save_rounded),
label: const Text("حفظ"),
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
textStyle: const TextStyle(
fontWeight: FontWeight.w700, fontSize: 16),
),
onPressed: () async {
if (selectedAmount == null || selectedAmount! <= 0) {
_showSnackBar(
'يرجى اختيار مبلغ صحيح أكبر من صفر',
);
return;
}
setState(() {
_transferList[index].amount = selectedAmount!;
if (_selectedMethod == 'yemenMobile' ||
_selectedMethod == 'sabafon') {
final pinStr = pinController.text.trim();
_transferList[index].pin =
pinStr.isEmpty ? '1234' : pinStr;
} else {
_transferList[index].pin = null;
}
});
await _saveTransferList();
Navigator.pop(context);
},
),
),
],
),
const SizedBox(height: 16),
],
),
);
},
);
},
);
}
}
ملاحظات على التعديلات:
- تم تعديل
ElevatedButton و OutlinedButton و TextButton في الثيم ليصبح شكلها أكثر حداثة مع زيادة الحواف (Radius)، الظلال (Shadow) ولون الخط.
- الأزرار التي لها وظيفة مهمة مثل "حفظ" و"إجراء التحويلات" و"تغيير" أضيفت لها أيقونات مناسبة بجانب النص.
- أزرار حوار المبالغ المحفوظة وإدارة الأرقام أصبحت تستخدم
FilledButton.icon أو OutlinedButton.icon مع أيقونات معبرة.
- في قائمة الأرقام السريعة، أضفت تأثير ظل بسيط للأزرار المحددة لتكون أكثر وضوحًا.
- زر التحويل أصبح يظهر مؤشر انتظار متحرك عند التنفيذ.
- شكل
AppBar وخلفيته محسنة مع تأثير تدرج ألوان و ظل.
يمكنك استخدام هذا الكود مباشرة في مشروعك ليعطي مظهرًا أجمل وأزراراً أكثر وضوحًا مع أيقونات ملائمة.
إذا أردت أي تعديل إضافي أو تبسيط لأي جزء، فقط أخبرني.