Files
BudgetApp/lib/pages/home/widgets/summary_widget.dart
T
Sanders 829ca93d9b Adds SMS reading functionality
Implements SMS reading functionality to automatically track expenses.

- Adds necessary permissions for reading SMS messages in AndroidManifest.xml.
- Registers SmsService and SmsCubit in the dependency injection container.
- Adds a new SMS page to the bottom navigation bar.
- Introduces new localization strings for the SMS page title and permission denied message.
- Sets minSdk to 23.
2025-06-30 13:40:52 +03:00

306 lines
11 KiB
Dart

import 'package:animated_digit/animated_digit.dart';
import 'package:budget_app/l10n/app_localizations.dart';
import 'package:budget_app/models/transaction_record.dart';
import 'package:budget_app/theme/custom_colors.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
// Изменение: Виджет преобразован в StatefulWidget для управления состоянием выбранного месяца.
class SummaryWidget extends StatefulWidget {
// Изменение: Виджет теперь принимает список всех транзакций, а не готовые суммы.
final List<TransactionRecord> transactions;
final String currencySymbol;
// Добавление: Принимает выбранный месяц и колбэк для его изменения от родителя.
final DateTime selectedMonth;
final ValueChanged<DateTime> onMonthChanged;
const SummaryWidget({
super.key,
required this.transactions,
required this.currencySymbol,
required this.selectedMonth,
required this.onMonthChanged,
});
@override
State<SummaryWidget> createState() => _SummaryWidgetState();
}
class _SummaryWidgetState extends State<SummaryWidget> {
// Добавление: PageController для управления PageView.
late PageController _pageController;
// Добавление: Хранение начального месяца для расчетов.
late DateTime _initialMonth;
// Добавление: Общее количество месяцев для отображения.
int _monthCount = 0;
@override
void initState() {
super.initState();
// Изменение: Находим самую раннюю транзакцию для определения начального месяца.
if (widget.transactions.isNotEmpty) {
widget.transactions.sort((a, b) => a.dateTime.compareTo(b.dateTime));
_initialMonth = DateTime(widget.transactions.first.dateTime.year,
widget.transactions.first.dateTime.month);
} else {
_initialMonth = DateTime(DateTime.now().year, DateTime.now().month);
}
_monthCount = _calculateMonthDifference(DateTime.now(), _initialMonth) + 1;
if (_monthCount < 1) _monthCount = 1; // Как минимум один месяц должен быть
// Инициализация PageController на последней странице (текущий месяц).
_pageController = PageController(initialPage: _monthCount - 1);
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
// Добавление: Вспомогательный метод для расчета разницы в месяцах.
int _calculateMonthDifference(DateTime d1, DateTime d2) {
return (d1.year - d2.year) * 12 + d1.month - d2.month;
}
// Добавление: Метод для форматирования названия месяца.
// Отображает год, если он отличается от текущего.
String _formatMonth(BuildContext context, DateTime date) {
final localizations = AppLocalizations.of(context)!;
final now = DateTime.now();
final format =
date.year == now.year ? DateFormat.MMMM(localizations.localeName) : DateFormat.yMMMM(localizations.localeName);
return format.format(date);
}
@override
Widget build(BuildContext context) {
return Card(
elevation: 8.0,
margin: const EdgeInsets.all(16.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
),
clipBehavior: Clip.antiAlias, // Обрезаем контент по границам карточки
child: SizedBox(
height: 300,
// Изменение: Используем Column для разделения PageView и индикатора.
child: Column(
children: [
// PageView будет занимать все доступное пространство.
Expanded(
child: PageView.builder(
controller: _pageController,
itemCount: _monthCount,
onPageChanged: (index) {
final newMonth = DateTime(
_initialMonth.year,
_initialMonth.month + index,
1,
);
widget.onMonthChanged(newMonth);
},
itemBuilder: (context, index) {
final month = DateTime(
_initialMonth.year,
_initialMonth.month + index,
1,
);
return _buildPage(context, month);
},
),
),
// Добавление: Индикатор теперь находится вне PageView.
Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: _buildPageIndicator(context),
),
],
),
),
);
}
// Добавление: Метод для построения одной страницы (одного месяца).
Widget _buildPage(BuildContext context, DateTime month) {
final localizations = AppLocalizations.of(context)!;
final customColors = Theme.of(context).extension<CustomColors>()!;
final theme = Theme.of(context);
final monthlyTransactions = widget.transactions.where((t) {
return t.dateTime.month == month.month && t.dateTime.year == month.year;
}).toList();
final income = monthlyTransactions
.where((t) => t.isIncome)
.fold(0.0, (sum, item) => sum + item.amount);
final expense = monthlyTransactions
.where((t) => !t.isIncome)
.fold(0.0, (sum, item) => sum + item.amount);
final balance = income - expense;
// Изменение: Уменьшены вертикальные отступы для предотвращения переполнения.
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 16.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
localizations.balance,
style: theme.textTheme.titleLarge?.copyWith(
color: customColors.accent,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8.0),
AnimatedDigitWidget(
value: balance,
fractionDigits: 2,
textStyle: theme.textTheme.displaySmall?.copyWith(
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurface,
),
suffix: ' ${widget.currencySymbol}',
),
const SizedBox(height: 16.0),
Divider(
height: 1,
thickness: 1,
color: customColors.divider,
),
const SizedBox(height: 16.0),
IntrinsicHeight(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildIncomeExpense(
context,
localizations.income,
income,
customColors.income!,
Icons.arrow_circle_up_outlined,
),
VerticalDivider(
width: 1,
thickness: 1,
color: customColors.divider,
),
_buildIncomeExpense(
context,
localizations.expense,
expense,
customColors.expense!,
Icons.arrow_circle_down_outlined,
),
],
),
),
const Spacer(), // Занимает оставшееся место
Text(
_formatMonth(context, month),
style: theme.textTheme.titleMedium?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.7),
),
),
// Удаление: Индикатор перенесен из страницы.
],
),
);
}
// Изменение: Индикатор теперь слушает PageController.
Widget _buildPageIndicator(BuildContext context) {
final customColors = Theme.of(context).extension<CustomColors>()!;
return AnimatedBuilder(
animation: _pageController,
builder: (context, child) {
// Проверяем, инициализирован ли контроллер
final page = _pageController.hasClients ? _pageController.page ?? 0 : _monthCount - 1.0;
final isFirstMonth = page < 0.5;
final isLastMonth = page > _monthCount - 1.5;
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Анимированная точка "назад"
AnimatedContainer(
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
width: isFirstMonth ? 0 : 8.0,
height: 8.0,
margin: EdgeInsets.symmetric(horizontal: isFirstMonth ? 0 : 4.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: customColors.divider,
),
),
// Активная точка
AnimatedContainer(
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
width: 12.0,
height: 12.0,
margin: const EdgeInsets.symmetric(horizontal: 4.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: customColors.accent,
),
),
// Анимированная точка "вперед"
AnimatedContainer(
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
width: isLastMonth ? 0 : 8.0,
height: 8.0,
margin: EdgeInsets.symmetric(horizontal: isLastMonth ? 0 : 4.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: customColors.divider,
),
),
],
);
},
);
}
Widget _buildIncomeExpense(
BuildContext context,
String title,
double amount,
Color color,
IconData icon,
) {
final theme = Theme.of(context);
return Expanded(
child: Column(
children: [
Icon(
icon,
color: color,
size: 32.0,
),
const SizedBox(height: 8.0),
Text(
title,
style: theme.textTheme.titleMedium,
),
const SizedBox(height: 4.0),
AnimatedDigitWidget(
value: amount,
fractionDigits: 2,
textStyle: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurface,
),
),
],
),
);
}
}