This commit refactors the user management system to utilize UserCubit, improving state management and separation of concerns. - Replaces UserService with UserCubit for managing user state. - Introduces AppSettings and GlobalSettings models and repositories for managing app-level settings and configurations. - Modifies dependency injection to register the new repositories and cubits. - Updates UI components (LoginPage, SettingsPage, HomePage, AddTransactionDialog, CategoryListPage, TagListPage) to interact with UserCubit and SettingsCubit. - Removes direct dependency on UserRepository in favor of UserCubit for accessing user information. - Streamlines the authentication process by using UserCubit to handle user creation and login. - Improves settings management by using dedicated repositories and cubits for app settings.
212 lines
8.4 KiB
Dart
212 lines
8.4 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import '../../theme/custom_colors.dart';
|
|
|
|
import '/l10n/app_localizations.dart';
|
|
import '../../logic/settings/settings_cubit.dart';
|
|
import '../../logic/transaction/transaction_bloc.dart';
|
|
import '../../logic/user/user_cubit.dart';
|
|
import '../home/widgets/summary_widget.dart'; // Импортируем новый виджет сводки
|
|
import '../reports_page.dart'; // Импортируем новую страницу отчетов
|
|
import '../settings_page.dart';
|
|
import '../sms/sms_page.dart';
|
|
import 'widgets/add_transaction_dialog.dart';
|
|
import 'widgets/transaction_item.dart'; // Импортируем новый виджет для элемента транзакции
|
|
|
|
class HomePage extends StatefulWidget {
|
|
const HomePage({super.key});
|
|
|
|
@override
|
|
State<HomePage> createState() => _HomePageState();
|
|
}
|
|
|
|
class _HomePageState extends State<HomePage> {
|
|
int _selectedIndex = 0; // Индекс выбранной вкладки
|
|
late String _currentUserId; // ID текущего пользователя
|
|
|
|
// Список виджетов для каждой вкладки нижней навигации
|
|
static final List<Widget> _widgetOptions = <Widget>[
|
|
const TransactionsPage(), // Главная страница с транзакциями
|
|
const ReportsPage(), // Страница отчетов
|
|
const SmsPage(), // Страница SMS
|
|
const SettingsPage(), // Страница настроек
|
|
];
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
// Получаем ID текущего пользователя из UserCubit
|
|
final userState = context.read<UserCubit>().state;
|
|
if (userState is UserLoaded && userState.user != null) {
|
|
_currentUserId = userState.user!.id;
|
|
// Загружаем транзакции через глобальный TransactionBloc
|
|
context.read<TransactionBloc>().add(LoadTransactions(userId: _currentUserId));
|
|
}
|
|
}
|
|
|
|
void _onItemTapped(int index) {
|
|
setState(() {
|
|
_selectedIndex = index;
|
|
});
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final localizations = AppLocalizations.of(
|
|
context,
|
|
)!; // Получаем экземпляр локализации
|
|
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: Text(localizations.appTitle), // Локализованный заголовок
|
|
// Кнопки действий в AppBar теперь не нужны, так как настройки перенесены в BottomNavigationBar
|
|
),
|
|
body: Center(
|
|
child: _widgetOptions[_selectedIndex], // Отображаем выбранный виджет
|
|
),
|
|
floatingActionButton: FloatingActionButton(
|
|
onPressed: () {
|
|
showDialog(
|
|
context: context,
|
|
builder: (BuildContext context) {
|
|
return const AddTransactionDialog();
|
|
},
|
|
);
|
|
},
|
|
child: const Icon(Icons.add),
|
|
),
|
|
bottomNavigationBar: BottomNavigationBar(
|
|
items: <BottomNavigationBarItem>[
|
|
BottomNavigationBarItem(
|
|
icon: const Icon(Icons.home),
|
|
label: localizations.homePageTitle, // Локализованный текст
|
|
),
|
|
BottomNavigationBarItem(
|
|
icon: const Icon(Icons.bar_chart),
|
|
label: localizations.reportsPageTitle, // Локализованный текст
|
|
),
|
|
BottomNavigationBarItem(
|
|
icon: const Icon(Icons.sms),
|
|
label: localizations.smsPageTitle,
|
|
),
|
|
BottomNavigationBarItem(
|
|
icon: const Icon(Icons.settings),
|
|
label: localizations.settingsPageTitle, // Локализованный текст
|
|
),
|
|
],
|
|
currentIndex: _selectedIndex,
|
|
selectedItemColor: Theme.of(context).colorScheme.primary,
|
|
unselectedItemColor: Theme.of(context).extension<CustomColors>()?.unselectedIcon,
|
|
onTap: _onItemTapped,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
// Изменение: TransactionsPage преобразован в StatefulWidget для управления состоянием выбранного месяца.
|
|
class TransactionsPage extends StatefulWidget {
|
|
const TransactionsPage({super.key});
|
|
|
|
@override
|
|
State<TransactionsPage> createState() => _TransactionsPageState();
|
|
}
|
|
|
|
class _TransactionsPageState extends State<TransactionsPage> {
|
|
// Добавление: Состояние для хранения выбранного месяца на уровне страницы.
|
|
late DateTime _selectedMonth;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
// Инициализация: Устанавливаем текущий месяц.
|
|
_selectedMonth = DateTime.now();
|
|
}
|
|
|
|
// Добавление: Метод для изменения месяца, который будет передаваться в SummaryWidget.
|
|
void _onMonthChanged(DateTime newMonth) {
|
|
setState(() {
|
|
_selectedMonth = newMonth;
|
|
});
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final localizations = AppLocalizations.of(context)!;
|
|
|
|
return BlocBuilder<TransactionBloc, TransactionState>(
|
|
builder: (context, state) {
|
|
if (state is TransactionLoading) {
|
|
return const Center(child: CircularProgressIndicator());
|
|
} else if (state is TransactionLoaded) {
|
|
// Добавление: Фильтрация транзакций по выбранному месяцу.
|
|
final monthlyTransactions = state.transactions.where((t) {
|
|
return t.dateTime.month == _selectedMonth.month && t.dateTime.year == _selectedMonth.year;
|
|
}).toList();
|
|
|
|
return ListView(
|
|
children: [
|
|
// Изменение: SummaryWidget теперь получает все транзакции,
|
|
// выбранный месяц и колбэк для его изменения.
|
|
BlocBuilder<SettingsCubit, SettingsState>(
|
|
builder: (context, settingsState) {
|
|
if (settingsState is SettingsLoaded) {
|
|
return SummaryWidget(
|
|
transactions: state.transactions,
|
|
selectedMonth: _selectedMonth,
|
|
onMonthChanged: _onMonthChanged,
|
|
currencySymbol: settingsState.defaultCurrency,
|
|
);
|
|
}
|
|
return SummaryWidget(
|
|
transactions: state.transactions,
|
|
selectedMonth: _selectedMonth,
|
|
onMonthChanged: _onMonthChanged,
|
|
currencySymbol: 'RUB',
|
|
);
|
|
},
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsets.all(16.0),
|
|
child: Text(
|
|
localizations.transactionsHistoryTitle,
|
|
style: Theme.of(context).textTheme.titleLarge,
|
|
),
|
|
),
|
|
// Изменение: Отображаем отфильтрованный список транзакций.
|
|
if (monthlyTransactions.isEmpty)
|
|
Center(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(16.0),
|
|
child: Text(localizations.noTransactionsText),
|
|
),
|
|
)
|
|
else
|
|
Card(
|
|
margin: const EdgeInsets.all(16.0),
|
|
elevation: 2,
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(12.0),
|
|
),
|
|
// Изменение: Используем отфильтрованный список.
|
|
child: ListView.builder(
|
|
shrinkWrap: true,
|
|
physics: const NeverScrollableScrollPhysics(),
|
|
itemCount: monthlyTransactions.length,
|
|
itemBuilder: (context, index) {
|
|
final transaction = monthlyTransactions[index];
|
|
return TransactionItem(transaction: transaction);
|
|
},
|
|
),
|
|
),
|
|
],
|
|
);
|
|
} else if (state is TransactionError) {
|
|
return Center(child: Text(localizations.transactionErrorText(state.message)));
|
|
} else {
|
|
return Center(child: Text(localizations.loadingTransactionsText));
|
|
}
|
|
},
|
|
);
|
|
}
|
|
}
|