mirror of
https://github.com/smmarty/friflex_flutter_starter.git
synced 2025-12-22 09:30:45 +00:00
Compare commits
2 Commits
main
...
feat/initi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72966ed2bb | ||
|
|
2bd6672fc4 |
@@ -1,16 +0,0 @@
|
||||
# friflex_starter
|
||||
|
||||
A new Flutter project.
|
||||
|
||||
## Getting Started
|
||||
|
||||
This project is a starting point for a Flutter application.
|
||||
|
||||
A few resources to get you started if this is your first Flutter project:
|
||||
|
||||
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
|
||||
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
|
||||
|
||||
For help getting started with Flutter development, view the
|
||||
[online documentation](https://docs.flutter.dev/), which offers tutorials,
|
||||
samples, guidance on mobile development, and a full API reference.
|
||||
29
app_services/aurora/app_services/.gitignore
vendored
29
app_services/aurora/app_services/.gitignore
vendored
@@ -1,29 +0,0 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
build/
|
||||
@@ -1,10 +0,0 @@
|
||||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: "7482962148e8d758338d8a28f589f317e1e42ba4"
|
||||
channel: "stable"
|
||||
|
||||
project_type: package
|
||||
@@ -1 +0,0 @@
|
||||
# Базовые сервисы для приложения
|
||||
@@ -1 +0,0 @@
|
||||
include: package:friflex_lint_rules/analysis_options.yaml
|
||||
@@ -1,4 +0,0 @@
|
||||
library app_services;
|
||||
|
||||
export 'src/app_path_provider.dart';
|
||||
export 'src/app_secure_storage.dart';
|
||||
@@ -1,13 +0,0 @@
|
||||
import 'package:i_app_services/i_app_services.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
/// Класс для Aurora реализации сервиса работы с путями
|
||||
class AppPathProvider implements IPathProvider {
|
||||
/// Наименование сервиса
|
||||
static const name = 'AuroraAppPathProvider';
|
||||
|
||||
@override
|
||||
Future<String> getAppDocumentsDirectoryPath() async {
|
||||
return (await getApplicationDocumentsDirectory()).path;
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:flutter_secure_storage_aurora/flutter_secure_storage_aurora.dart';
|
||||
import 'package:i_app_services/i_app_services.dart';
|
||||
|
||||
/// Класс для Aurora реализации сервис по работе с защищенным хранилищем
|
||||
final class AppSecureStorage implements ISecureStorage {
|
||||
/// Создает сервис для работы с защищенным хранилищем
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [secretKey] - ключ шифрования данных
|
||||
AppSecureStorage({required this.secretKey}){
|
||||
FlutterSecureStorageAurora.setSecret(secretKey);
|
||||
}
|
||||
|
||||
@override
|
||||
final String secretKey;
|
||||
|
||||
|
||||
static const name = 'AuroraAppSecureStorage';
|
||||
|
||||
/// Экземпляр хранилища данных
|
||||
final _box = const FlutterSecureStorage();
|
||||
|
||||
@override
|
||||
Future<void> clear() async {
|
||||
await _box.deleteAll();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> delete(String key) async {
|
||||
await _box.delete(key: key);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> exists(String key) {
|
||||
return _box.containsKey(key: key);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> read(String key) async {
|
||||
return _box.read(key: key);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> write(String key, String value) async {
|
||||
await _box.write(key: key, value: value);
|
||||
}
|
||||
|
||||
@override
|
||||
String get nameImpl => AppSecureStorage.name;
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
name: app_services
|
||||
description: "Google сервисы для приложения"
|
||||
version: 0.0.1
|
||||
publish_to: none
|
||||
|
||||
environment:
|
||||
sdk: ^3.5.0
|
||||
flutter: ^3.24.0
|
||||
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
|
||||
# Зависимости для сервиса защищенного хранилища
|
||||
flutter_secure_storage: 8.0.0
|
||||
flutter_secure_storage_aurora:
|
||||
git:
|
||||
url: https://gitlab.com/omprussia/flutter/flutter-community-plugins/flutter_secure_storage_aurora.git
|
||||
ref: aurora-0.5.3
|
||||
|
||||
# для работы с путями в хранилища
|
||||
path_provider: 2.1.4
|
||||
path_provider_aurora:
|
||||
git:
|
||||
url: https://gitlab.com/omprussia/flutter/packages.git
|
||||
ref: aurora-path_provider_aurora-0.6.0
|
||||
path: packages/path_provider_aurora
|
||||
|
||||
# Обязательные интерфейсы
|
||||
i_app_services:
|
||||
path: ../../i_app_services
|
||||
|
||||
dev_dependencies:
|
||||
friflex_lint_rules:
|
||||
hosted: https://pub.friflex.com
|
||||
version: 4.0.1
|
||||
29
app_services/gms/app_services/.gitignore
vendored
29
app_services/gms/app_services/.gitignore
vendored
@@ -1,29 +0,0 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
build/
|
||||
@@ -1,10 +0,0 @@
|
||||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: "7482962148e8d758338d8a28f589f317e1e42ba4"
|
||||
channel: "stable"
|
||||
|
||||
project_type: package
|
||||
@@ -1 +0,0 @@
|
||||
# Базовые сервисы для приложения
|
||||
@@ -1 +0,0 @@
|
||||
include: package:friflex_lint_rules/analysis_options.yaml
|
||||
@@ -1,4 +0,0 @@
|
||||
library app_services;
|
||||
|
||||
export 'src/app_path_provider.dart';
|
||||
export 'src/app_secure_storage.dart';
|
||||
@@ -1,13 +0,0 @@
|
||||
import 'package:i_app_services/i_app_services.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
/// Класс для базовой реализации сервиса работы с путями
|
||||
class AppPathProvider implements IPathProvider {
|
||||
/// Наименование сервиса
|
||||
static const name = 'GmsAppPathProvider';
|
||||
|
||||
@override
|
||||
Future<String> getAppDocumentsDirectoryPath() async {
|
||||
return (await getApplicationDocumentsDirectory()).path;
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:i_app_services/i_app_services.dart';
|
||||
|
||||
/// Класс для базовой реализации сервис по работе с защищенным хранилищем
|
||||
final class AppSecureStorage implements ISecureStorage {
|
||||
/// Создает сервис для работы с защищенным хранилищем
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [secretKey] - ключ шифрования данных
|
||||
AppSecureStorage({required this.secretKey});
|
||||
|
||||
@override
|
||||
final String secretKey;
|
||||
|
||||
static const name = 'GmsAppSecureStorage';
|
||||
|
||||
/// Экземпляр хранилища данных
|
||||
final _box = const FlutterSecureStorage();
|
||||
|
||||
@override
|
||||
Future<void> clear() async {
|
||||
await _box.deleteAll();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> delete(String key) async {
|
||||
await _box.delete(key: key);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> exists(String key) {
|
||||
return _box.containsKey(key: key);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> read(String key) async {
|
||||
return _box.read(key: key);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> write(String key, String value) async {
|
||||
await _box.write(key: key, value: value);
|
||||
}
|
||||
|
||||
@override
|
||||
String get nameImpl => AppSecureStorage.name;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
name: app_services
|
||||
description: "Google сервисы для приложения"
|
||||
version: 0.0.1
|
||||
publish_to: none
|
||||
|
||||
environment:
|
||||
sdk: ^3.5.0
|
||||
flutter: ^3.24.0
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
|
||||
# Зависимости для сервиса защищенного хранилища
|
||||
flutter_secure_storage: 9.2.4
|
||||
|
||||
# Зависимости для сервиса незащищенного хранилища
|
||||
shared_preferences: 2.3.5
|
||||
|
||||
# для работы с путями в хранилища
|
||||
path_provider: 2.1.5
|
||||
|
||||
# Обязательные интерфейсы
|
||||
i_app_services:
|
||||
path: ../../i_app_services
|
||||
|
||||
dev_dependencies:
|
||||
friflex_lint_rules:
|
||||
hosted: https://pub.friflex.com
|
||||
version: 4.0.1
|
||||
29
app_services/i_app_services/.gitignore
vendored
29
app_services/i_app_services/.gitignore
vendored
@@ -1,29 +0,0 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
build/
|
||||
@@ -1 +0,0 @@
|
||||
# Хранит в себе все интерфейсы для реализации общих сервисов
|
||||
@@ -1,10 +0,0 @@
|
||||
include: package:friflex_lint_rules/analysis_options.yaml
|
||||
|
||||
analyzer:
|
||||
exclude:
|
||||
- "**/*.g.dart"
|
||||
- "**/*.freezed.dart"
|
||||
- "**/*.yaml"
|
||||
- "app_services/aurora/**"
|
||||
- "/app_services/aurora/**"
|
||||
- "**/app_services/aurora/**"
|
||||
@@ -1,4 +0,0 @@
|
||||
library i_app_services;
|
||||
|
||||
export 'src/i_path_provider.dart';
|
||||
export 'src/i_secure_storage.dart';
|
||||
@@ -1,9 +0,0 @@
|
||||
/// Класс для описания интерфейса сервиса
|
||||
/// для получения пути хранения файлов
|
||||
abstract interface class IPathProvider {
|
||||
/// Наименования интерфейса
|
||||
static const name = 'IPathProvider';
|
||||
|
||||
/// Получение path на внутренне хранилище приложения
|
||||
Future<String> getAppDocumentsDirectoryPath();
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
/// Класс интерфейса для работы с защищенным хранилищем
|
||||
abstract interface class ISecureStorage {
|
||||
/// Описывает обязательные параметры имплементаций
|
||||
///
|
||||
/// Требует:
|
||||
/// - [secretKey] - секретный ключ для шифрования данных
|
||||
const ISecureStorage._({
|
||||
required this.secretKey,
|
||||
});
|
||||
|
||||
/// Секретный ключ для шифрования данных
|
||||
final String secretKey;
|
||||
|
||||
/// Наименования интерфейса
|
||||
static const name = 'ISecureStorage';
|
||||
|
||||
/// Метод для получения значения из защищенного хранилища
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [key] - ключ
|
||||
Future<String?> read(String key);
|
||||
|
||||
/// Метод для записи значения в защищенное хранилище
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [key] - ключ
|
||||
/// - [value] - значение
|
||||
Future<void> write(String key, String value);
|
||||
|
||||
/// Метод для удаления значения из защищенного хранилища
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [key] - ключ
|
||||
Future<void> delete(String key);
|
||||
|
||||
/// Метод для очистки защищенного хранилища
|
||||
Future<void> clear();
|
||||
|
||||
/// Метод для проверки наличия значения в защищенном хранилище
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [key] - ключ
|
||||
Future<bool> exists(String key);
|
||||
|
||||
String get nameImpl;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
name: i_app_services
|
||||
description: "Хранит в себе все интерфейсы для реализации общих сервисов"
|
||||
version: 0.0.1
|
||||
publish_to: "none"
|
||||
|
||||
environment:
|
||||
sdk: ^3.5.0
|
||||
flutter: ^3.24.0
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
|
||||
dev_dependencies:
|
||||
friflex_lint_rules:
|
||||
hosted: https://pub.friflex.com
|
||||
version: 4.0.1
|
||||
@@ -1,5 +0,0 @@
|
||||
arb-dir: lib/l10n
|
||||
template-arb-file: app_en.arb
|
||||
output-dir: lib/l10n/gen
|
||||
output-localization-file: app_localizations.dart
|
||||
synthetic-package: false
|
||||
111
lib/app/app.dart
111
lib/app/app.dart
@@ -1,111 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/app/app_context_ext.dart';
|
||||
import 'package:friflex_starter/app/app_providers.dart';
|
||||
import 'package:friflex_starter/app/depends_providers.dart';
|
||||
import 'package:friflex_starter/app/theme/app_theme.dart';
|
||||
import 'package:friflex_starter/app/theme/theme_notifier.dart';
|
||||
import 'package:friflex_starter/di/di_container.dart';
|
||||
import 'package:friflex_starter/features/error/error_screen.dart';
|
||||
import 'package:friflex_starter/features/splash/splash_screen.dart';
|
||||
import 'package:friflex_starter/l10n/gen/app_localizations.dart';
|
||||
import 'package:friflex_starter/l10n/localization_notifier.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
/// Класс приложения
|
||||
class App extends StatefulWidget {
|
||||
const App({
|
||||
super.key,
|
||||
required this.router,
|
||||
required this.initDependencies,
|
||||
});
|
||||
/// Роутер приложения
|
||||
final GoRouter router;
|
||||
/// Функция для инициализации зависимостей
|
||||
final Future<DiContainer> Function() initDependencies;
|
||||
|
||||
@override
|
||||
State<App> createState() => _AppState();
|
||||
}
|
||||
|
||||
class _AppState extends State<App> {
|
||||
/// Мутабельная Future для инициализации зависимостей
|
||||
late Future<DiContainer> _initFuture;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initFuture = widget.initDependencies();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AppProviders(
|
||||
// Consumer для локализации добавляем выше чем DependsProviders
|
||||
// чтобы при изменении локализации перестраивался весь виджет
|
||||
// Но, это не обязательно, можно добавить в DependsProviders
|
||||
child: LocalizationConsumer(
|
||||
builder: () => FutureBuilder<DiContainer>(
|
||||
future: _initFuture,
|
||||
builder: (_, snapshot) {
|
||||
switch (snapshot.connectionState) {
|
||||
case ConnectionState.none:
|
||||
case ConnectionState.waiting:
|
||||
case ConnectionState.active:
|
||||
// Пока инициализация показываем Splash
|
||||
return const SplashScreen();
|
||||
case ConnectionState.done:
|
||||
if (snapshot.hasError) {
|
||||
return ErrorScreen(
|
||||
error: snapshot.error,
|
||||
stackTrace: snapshot.stackTrace,
|
||||
onRetry: _retryInit,
|
||||
);
|
||||
}
|
||||
|
||||
final diContainer = snapshot.data;
|
||||
if (diContainer == null) {
|
||||
return ErrorScreen(
|
||||
error:
|
||||
'Ошибка инициализации зависимостей, diContainer = null',
|
||||
stackTrace: null,
|
||||
onRetry: _retryInit,
|
||||
);
|
||||
}
|
||||
return DependsProviders(
|
||||
diContainer: diContainer,
|
||||
child: ThemeConsumer(
|
||||
builder: () => _App(router: widget.router),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _retryInit() {
|
||||
setState(() {
|
||||
_initFuture = widget.initDependencies();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _App extends StatelessWidget {
|
||||
const _App({required this.router});
|
||||
|
||||
final GoRouter router;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp.router(
|
||||
routerConfig: router,
|
||||
darkTheme: AppTheme.dark,
|
||||
theme: AppTheme.light,
|
||||
themeMode: context.theme.themeMode,
|
||||
locale: context.localization.locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import 'package:envied/envied.dart';
|
||||
import 'package:friflex_starter/app/app_config/i_app_config.dart';
|
||||
import 'package:friflex_starter/app/app_env.dart';
|
||||
|
||||
part 'app_config.g.dart';
|
||||
|
||||
/// Класс для реализации конфигурации с моковыми данными
|
||||
@Envied(name: 'Dev', path: 'env/dev.env')
|
||||
class AppConfigDev implements IAppConfig {
|
||||
@override
|
||||
AppEnv get env => AppEnv.dev;
|
||||
|
||||
@override
|
||||
String get name => 'AppConfigDev';
|
||||
|
||||
@override
|
||||
@EnviedField()
|
||||
final String baseUrl = _Dev.baseUrl;
|
||||
|
||||
@override
|
||||
@EnviedField(obfuscate: true)
|
||||
final String secretKey = _Dev.secretKey;
|
||||
}
|
||||
|
||||
/// Класс для реализации конфигурации с продакшн данными
|
||||
@Envied(name: 'Prod', path: 'env/prod.env')
|
||||
class AppConfigProd implements IAppConfig {
|
||||
@override
|
||||
AppEnv get env => AppEnv.prod;
|
||||
|
||||
@override
|
||||
String get name => 'AppConfigProd';
|
||||
|
||||
@override
|
||||
@EnviedField(obfuscate: true)
|
||||
final String baseUrl = _Prod.baseUrl;
|
||||
|
||||
@override
|
||||
@EnviedField(obfuscate: true)
|
||||
final String secretKey = _Prod.secretKey;
|
||||
}
|
||||
|
||||
/// Класс для реализации конфигурации с стейдж данными
|
||||
@Envied(name: 'Stage', path: 'env/stage.env')
|
||||
class AppConfigStage implements IAppConfig {
|
||||
@override
|
||||
AppEnv get env => AppEnv.stage;
|
||||
|
||||
@override
|
||||
String get name => 'AppConfigStage';
|
||||
|
||||
@override
|
||||
@EnviedField(obfuscate: true)
|
||||
final String baseUrl = _Stage.baseUrl;
|
||||
|
||||
@override
|
||||
@EnviedField(obfuscate: true)
|
||||
final String secretKey = _Stage.secretKey;
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'app_config.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// EnviedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint
|
||||
// generated_from: env/dev.env
|
||||
final class _Dev {
|
||||
static const String baseUrl = 'https://dev';
|
||||
|
||||
static const List<int> _enviedkeysecretKey = <int>[
|
||||
45820206,
|
||||
4292305074,
|
||||
1553598735,
|
||||
];
|
||||
|
||||
static const List<int> _envieddatasecretKey = <int>[
|
||||
45820234,
|
||||
4292305111,
|
||||
1553598841,
|
||||
];
|
||||
|
||||
static final String secretKey = String.fromCharCodes(List<int>.generate(
|
||||
_envieddatasecretKey.length,
|
||||
(int i) => i,
|
||||
growable: false,
|
||||
).map((int i) => _envieddatasecretKey[i] ^ _enviedkeysecretKey[i]));
|
||||
}
|
||||
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint
|
||||
// generated_from: env/prod.env
|
||||
final class _Prod {
|
||||
static const List<int> _enviedkeybaseUrl = <int>[
|
||||
3619294633,
|
||||
560029786,
|
||||
3178585068,
|
||||
3377720392,
|
||||
977735066,
|
||||
2142081055,
|
||||
1298585806,
|
||||
933917938,
|
||||
1244996901,
|
||||
1950368931,
|
||||
2147265964,
|
||||
2338251746,
|
||||
];
|
||||
|
||||
static const List<int> _envieddatabaseUrl = <int>[
|
||||
3619294657,
|
||||
560029742,
|
||||
3178584984,
|
||||
3377720376,
|
||||
977735145,
|
||||
2142081061,
|
||||
1298585825,
|
||||
933917917,
|
||||
1244996949,
|
||||
1950368977,
|
||||
2147265987,
|
||||
2338251654,
|
||||
];
|
||||
|
||||
static final String baseUrl = String.fromCharCodes(List<int>.generate(
|
||||
_envieddatabaseUrl.length,
|
||||
(int i) => i,
|
||||
growable: false,
|
||||
).map((int i) => _envieddatabaseUrl[i] ^ _enviedkeybaseUrl[i]));
|
||||
|
||||
static const List<int> _enviedkeysecretKey = <int>[
|
||||
2449171331,
|
||||
2315988352,
|
||||
1037757119,
|
||||
3159274193,
|
||||
];
|
||||
|
||||
static const List<int> _envieddatasecretKey = <int>[
|
||||
2449171443,
|
||||
2315988466,
|
||||
1037757136,
|
||||
3159274165,
|
||||
];
|
||||
|
||||
static final String secretKey = String.fromCharCodes(List<int>.generate(
|
||||
_envieddatasecretKey.length,
|
||||
(int i) => i,
|
||||
growable: false,
|
||||
).map((int i) => _envieddatasecretKey[i] ^ _enviedkeysecretKey[i]));
|
||||
}
|
||||
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint
|
||||
// generated_from: env/stage.env
|
||||
final class _Stage {
|
||||
static const List<int> _enviedkeybaseUrl = <int>[
|
||||
443716089,
|
||||
3928907238,
|
||||
1851881210,
|
||||
3858110087,
|
||||
3324475128,
|
||||
1601592105,
|
||||
2404110281,
|
||||
1092690431,
|
||||
1025677374,
|
||||
3283672546,
|
||||
425122182,
|
||||
3412521909,
|
||||
1297182020,
|
||||
];
|
||||
|
||||
static const List<int> _envieddatabaseUrl = <int>[
|
||||
443715985,
|
||||
3928907154,
|
||||
1851881102,
|
||||
3858110199,
|
||||
3324475019,
|
||||
1601592083,
|
||||
2404110310,
|
||||
1092690384,
|
||||
1025677389,
|
||||
3283672470,
|
||||
425122279,
|
||||
3412521938,
|
||||
1297181985,
|
||||
];
|
||||
|
||||
static final String baseUrl = String.fromCharCodes(List<int>.generate(
|
||||
_envieddatabaseUrl.length,
|
||||
(int i) => i,
|
||||
growable: false,
|
||||
).map((int i) => _envieddatabaseUrl[i] ^ _enviedkeybaseUrl[i]));
|
||||
|
||||
static const List<int> _enviedkeysecretKey = <int>[
|
||||
58874248,
|
||||
3497500657,
|
||||
3833421599,
|
||||
555777488,
|
||||
132619188,
|
||||
];
|
||||
|
||||
static const List<int> _envieddatasecretKey = <int>[
|
||||
58874363,
|
||||
3497500549,
|
||||
3833421694,
|
||||
555777463,
|
||||
132619217,
|
||||
];
|
||||
|
||||
static final String secretKey = String.fromCharCodes(List<int>.generate(
|
||||
_envieddatasecretKey.length,
|
||||
(int i) => i,
|
||||
growable: false,
|
||||
).map((int i) => _envieddatasecretKey[i] ^ _enviedkeysecretKey[i]));
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import 'package:friflex_starter/app/app_env.dart';
|
||||
|
||||
/// Класс для описания интерфейса конфигурации
|
||||
abstract interface class IAppConfig {
|
||||
/// Наименование сервиса
|
||||
String get name => 'IAppConfig';
|
||||
|
||||
/// Основной адрес для запросов к API
|
||||
String get baseUrl;
|
||||
|
||||
/// Тип окружения
|
||||
AppEnv get env;
|
||||
|
||||
/// Секретный ключ для шифрования данных
|
||||
String get secretKey;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/app/theme/theme_notifier.dart';
|
||||
import 'package:friflex_starter/di/di_container.dart';
|
||||
import 'package:friflex_starter/l10n/gen/app_localizations.dart';
|
||||
import 'package:friflex_starter/l10n/localization_notifier.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
/// Класс, реализующий расширение для контекста приложения
|
||||
extension AppContextExt on BuildContext {
|
||||
/// Метод для получения экземпляра DIContainer
|
||||
DiContainer get di => read<DiContainer>();
|
||||
|
||||
/// Геттер для получения цветовой схемы
|
||||
ColorScheme get colors => Theme.of(this).colorScheme;
|
||||
|
||||
/// Геттер для получения темы
|
||||
ThemeNotifier get theme => read<ThemeNotifier>();
|
||||
|
||||
/// Геттер для получения локализации
|
||||
AppLocalizations get l10n => AppLocalizations.of(this)!;
|
||||
|
||||
/// Геттер для получения управления локализацией
|
||||
LocalizationNotifier get localization => read<LocalizationNotifier>();
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
/// Перечислимый тип окружений сборки
|
||||
enum AppEnv {
|
||||
/// Тестовое окружение (моковое)
|
||||
dev,
|
||||
|
||||
/// Стейдж окружение (тестовое окружение, которое имеет возможность
|
||||
/// как обращаться в сеть, так и использовать моковые данные)
|
||||
stage,
|
||||
|
||||
/// Продакшен окружение
|
||||
prod,
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/app/theme/theme_notifier.dart';
|
||||
import 'package:friflex_starter/l10n/localization_notifier.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
/// Класс для добавления провайдеров темы и локализации
|
||||
final class AppProviders extends StatelessWidget {
|
||||
const AppProviders({
|
||||
super.key,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider(
|
||||
create: (_) => ThemeNotifier(),
|
||||
), // Провайдер для темы
|
||||
ChangeNotifierProvider(
|
||||
create: (_) => LocalizationNotifier(),
|
||||
), // Провайдер для локализации
|
||||
],
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/di/di_container.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
/// Класс для внедрения глобальных зависимостей
|
||||
final class DependsProviders extends StatelessWidget {
|
||||
const DependsProviders({
|
||||
super.key,
|
||||
required this.child,
|
||||
required this.diContainer,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
final DiContainer diContainer;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
// Сюда добавляем глобальные блоки, inherited и т.д.
|
||||
Provider.value(value: diContainer), // Передаем контейнер зависимостей
|
||||
],
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:friflex_starter/app/app_config/i_app_config.dart';
|
||||
import 'package:friflex_starter/app/http/i_http_client.dart';
|
||||
import 'package:friflex_starter/features/debug/i_debug_service.dart';
|
||||
|
||||
/// Класс для реализации HTTP-клиента для управления запросами
|
||||
final class AppHttpClient implements IHttpClient {
|
||||
/// Создает HTTP клиент
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [debugService] - сервис для логирования запросов
|
||||
/// - [appConfig] - конфигурация приложения
|
||||
AppHttpClient({
|
||||
required IDebugService debugService,
|
||||
required IAppConfig appConfig,
|
||||
}) {
|
||||
_httpClient = Dio();
|
||||
_appConfig = appConfig;
|
||||
|
||||
_httpClient.options
|
||||
..baseUrl = appConfig.baseUrl
|
||||
..connectTimeout = const Duration(seconds: 5)
|
||||
..sendTimeout = const Duration(seconds: 7)
|
||||
..receiveTimeout = const Duration(seconds: 10)
|
||||
..headers = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
debugService.log('HTTP client created');
|
||||
}
|
||||
|
||||
/// Конфигурация приложения
|
||||
late final IAppConfig _appConfig;
|
||||
|
||||
/// Экземпляр HTTP клиента
|
||||
late final Dio _httpClient;
|
||||
|
||||
@override
|
||||
Future<Response> get(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
}) async {
|
||||
_httpClient.options.baseUrl = _appConfig.baseUrl;
|
||||
|
||||
return _httpClient.get(
|
||||
path,
|
||||
data: data,
|
||||
queryParameters: queryParameters,
|
||||
options: options,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response> post(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
}) async {
|
||||
_httpClient.options.baseUrl = _appConfig.baseUrl;
|
||||
|
||||
return _httpClient.post(
|
||||
path,
|
||||
data: data,
|
||||
queryParameters: queryParameters,
|
||||
options: options,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response> patch(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
}) async {
|
||||
_httpClient.options.baseUrl = _appConfig.baseUrl;
|
||||
|
||||
return _httpClient.patch(
|
||||
path,
|
||||
data: data,
|
||||
queryParameters: queryParameters,
|
||||
options: options,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response> put(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
}) async {
|
||||
_httpClient.options.baseUrl = _appConfig.baseUrl;
|
||||
|
||||
return _httpClient.put(
|
||||
path,
|
||||
data: data,
|
||||
queryParameters: queryParameters,
|
||||
options: options,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response> delete(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
}) async {
|
||||
_httpClient.options.baseUrl = _appConfig.baseUrl;
|
||||
|
||||
return _httpClient.delete(
|
||||
path,
|
||||
data: data,
|
||||
queryParameters: queryParameters,
|
||||
options: options,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response> head(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
}) async {
|
||||
_httpClient.options.baseUrl = _appConfig.baseUrl;
|
||||
|
||||
return _httpClient.head(
|
||||
path,
|
||||
data: data,
|
||||
queryParameters: queryParameters,
|
||||
options: options,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
/// Класс для описания интерфейса сервиса по управлению HTTP запросами
|
||||
abstract interface class IHttpClient {
|
||||
/// Описывает поля HTTP клиента
|
||||
const IHttpClient();
|
||||
|
||||
/// Наименование сервиса
|
||||
static const name = 'IHttpClient';
|
||||
|
||||
/// Метод для реализации запроса GET
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [path] - путь к ресурсу
|
||||
/// - [data] - тело запроса
|
||||
/// - [queryParameters] - параметры запроса
|
||||
/// - [options] - конфигурация запроса
|
||||
Future<Response> get(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
});
|
||||
|
||||
/// Метод для реализации запроса POST
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [path] - путь к ресурсу
|
||||
/// - [data] - тело запроса
|
||||
/// - [queryParameters] - параметры запроса
|
||||
/// - [options] - конфигурация запроса
|
||||
Future<Response> post(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
});
|
||||
|
||||
/// Метод для реализации запроса PATCH
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [path] - путь к ресурсу
|
||||
/// - [data] - тело запроса
|
||||
/// - [queryParameters] - параметры запроса
|
||||
/// - [options] - конфигурация запроса
|
||||
Future<Response> patch(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
});
|
||||
|
||||
/// Метод для реализации запроса PUT
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [path] - путь к ресурсу
|
||||
/// - [data] - тело запроса
|
||||
/// - [queryParameters] - параметры запроса
|
||||
/// - [options] - конфигурация запроса
|
||||
Future<Response> put(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
});
|
||||
|
||||
/// Метод для реализации запроса DELETE
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [path] - путь к ресурсу
|
||||
/// - [data] - тело запроса
|
||||
/// - [queryParameters] - параметры запроса
|
||||
/// - [options] - конфигурация запроса
|
||||
Future<Response> delete(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
});
|
||||
|
||||
/// Метод для реализации запроса POST
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [path] - путь к ресурсу
|
||||
/// - [data] - тело запроса
|
||||
/// - [queryParameters] - параметры запроса
|
||||
/// - [options] - конфигурация запроса
|
||||
Future<Response> head(
|
||||
String path, {
|
||||
Object? data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
});
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Класс, реализующий расширение для добавления токенов в цветовую схему
|
||||
extension AppColorsScheme on ColorScheme {
|
||||
bool get _isDark => brightness == Brightness.dark;
|
||||
|
||||
// Тестовый цвет
|
||||
Color get testColor => _isDark ? Colors.green : Colors.red;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Класс для конфигурации светлой/темной темы приложения
|
||||
abstract class AppTheme {
|
||||
/// Геттер для получения светлой темы
|
||||
static ThemeData get light => ThemeData.light();
|
||||
|
||||
/// Геттер для получения темной темы
|
||||
static ThemeData get dark => ThemeData.dark();
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
typedef ThemeBuilder = Widget Function();
|
||||
|
||||
/// Виджет для подписки на изменение темы приложения
|
||||
class ThemeConsumer extends StatelessWidget {
|
||||
const ThemeConsumer({super.key, required this.builder});
|
||||
|
||||
final ThemeBuilder builder;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Consumer<ThemeNotifier>(
|
||||
builder: (_, __, ___) {
|
||||
return builder();
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Класс для управления темой приложения
|
||||
final class ThemeNotifier extends ChangeNotifier {
|
||||
ThemeMode _themeMode = ThemeMode.system;
|
||||
|
||||
ThemeMode get themeMode => _themeMode;
|
||||
|
||||
void changeTheme() {
|
||||
_themeMode =
|
||||
_themeMode == ThemeMode.light ? ThemeMode.dark : ThemeMode.light;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
/// Миксин репозитория в приложении.
|
||||
/// Каждый интерфейс репозитория в приложении должен подмешивать текущий класс
|
||||
mixin class DiBaseRepo {
|
||||
/// Наименование репозитория
|
||||
String get name => 'DiBaseRepo';
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import 'package:friflex_starter/app/app_config/app_config.dart';
|
||||
import 'package:friflex_starter/app/app_config/i_app_config.dart';
|
||||
import 'package:friflex_starter/app/app_env.dart';
|
||||
import 'package:friflex_starter/app/http/app_http_client.dart';
|
||||
import 'package:friflex_starter/app/http/i_http_client.dart';
|
||||
import 'package:friflex_starter/di/di_repositories.dart';
|
||||
import 'package:friflex_starter/di/di_services.dart';
|
||||
import 'package:friflex_starter/di/di_typedefs.dart';
|
||||
import 'package:friflex_starter/features/debug/i_debug_service.dart';
|
||||
|
||||
/// {@template dependencies_container}
|
||||
/// Контейнер для зависимостей
|
||||
/// {@macro composition_process}
|
||||
/// {@endtemplate}
|
||||
final class DiContainer {
|
||||
/// {@macro dependencies_container}
|
||||
DiContainer({required this.env, required IDebugService dService})
|
||||
: debugService = dService;
|
||||
final AppEnv env;
|
||||
|
||||
/// Сервис для отладки, получаем из конструктора
|
||||
late final IDebugService debugService;
|
||||
|
||||
/// Конфигурация приложения
|
||||
late final IAppConfig appConfig;
|
||||
|
||||
/// Сервис для работы с HTTP запросами
|
||||
late final IHttpClient Function(IDebugService, IAppConfig) httpClientFactory;
|
||||
|
||||
/// Репозитории приложения
|
||||
late final DiRepositories repositories;
|
||||
|
||||
/// Сервисы приложения
|
||||
late final DiServices services;
|
||||
|
||||
/// Метод для инициализации зависимостей
|
||||
Future<void> init({
|
||||
required OnProgress onProgress,
|
||||
required OnComplete onComplete,
|
||||
required OnError onError,
|
||||
}) async {
|
||||
// Инициализация конфигурации приложения
|
||||
appConfig = switch (env) {
|
||||
AppEnv.dev => AppConfigDev(),
|
||||
AppEnv.prod => AppConfigProd(),
|
||||
AppEnv.stage => AppConfigStage()
|
||||
};
|
||||
|
||||
// Инициализация HTTP клиента
|
||||
httpClientFactory = (debugService, appConfig) => AppHttpClient(
|
||||
debugService: debugService,
|
||||
appConfig: appConfig,
|
||||
);
|
||||
|
||||
// Инициализация сервисов
|
||||
services = DiServices()
|
||||
..init(
|
||||
onProgress: onProgress,
|
||||
onError: onError,
|
||||
diContainer: this,
|
||||
);
|
||||
// throw Exception('Тестовая - ошибка инициализации зависимостей');
|
||||
// Инициализация репозиториев
|
||||
repositories = DiRepositories()
|
||||
..init(
|
||||
onProgress: onProgress,
|
||||
onError: onError,
|
||||
diContainer: this,
|
||||
);
|
||||
|
||||
onComplete('Инициализация зависимостей завершена!');
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
import 'package:friflex_starter/app/app_env.dart';
|
||||
import 'package:friflex_starter/di/di_base_repo.dart';
|
||||
import 'package:friflex_starter/di/di_container.dart';
|
||||
import 'package:friflex_starter/di/di_typedefs.dart';
|
||||
import 'package:friflex_starter/features/auth/data/repository/auth_mock_repository.dart';
|
||||
import 'package:friflex_starter/features/auth/data/repository/auth_repository.dart';
|
||||
import 'package:friflex_starter/features/auth/domain/repository/i_auth_repository.dart';
|
||||
import 'package:friflex_starter/features/main/data/repository/main_mock_repository.dart';
|
||||
import 'package:friflex_starter/features/main/data/repository/main_repository.dart';
|
||||
import 'package:friflex_starter/features/main/domain/repository/i_main_repository.dart';
|
||||
import 'package:friflex_starter/features/profile/data/repository/profile_mock_repository.dart';
|
||||
import 'package:friflex_starter/features/profile/data/repository/profile_repository.dart';
|
||||
import 'package:friflex_starter/features/profile/domain/repository/i_profile_repository.dart';
|
||||
import 'package:friflex_starter/features/profile_scope/data/repository/profile_scope_mock_repository.dart';
|
||||
import 'package:friflex_starter/features/profile_scope/data/repository/profile_scope_repository.dart';
|
||||
import 'package:friflex_starter/features/profile_scope/domain/repository/i_profile_scope_repository.dart';
|
||||
|
||||
/// Список названий моковых репозиториев, которые должны быть подменены
|
||||
/// для использования в сборке stage окружения
|
||||
///
|
||||
/// Для того, чтобы репозиторий был автоматически подменен на моковый в stage
|
||||
/// сборке, необходимо в этом списке указать название мокового репозитория,
|
||||
/// обращаясь к соответствующему полю name.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```
|
||||
/// [ AuthCheckRepositoryMock().name, ]
|
||||
/// ```
|
||||
final List<String> _mockReposToSwitch = [];
|
||||
|
||||
/// Класс для инициализации репозиториев в приложении
|
||||
///
|
||||
/// По умолчанию репозиторию присваивается моковая реализация.
|
||||
/// В зависимости от окружения либо выполняется подмена репозиторий,
|
||||
/// либо используется моковый.
|
||||
final class DiRepositories {
|
||||
/// Интерфейс для работы с репозиторием авторизации
|
||||
late final IAuthRepository authRepository;
|
||||
|
||||
/// Интерфейс для работы с репозиторием главного сервиса
|
||||
late final IMainRepository mainRepository;
|
||||
|
||||
/// Интерфейс для работы с репозиторием профиля
|
||||
late final IProfileRepository profileRepository;
|
||||
|
||||
/// Интерфейс для работы с репозиторием профиля scope
|
||||
late final IProfileScopeRepository profileScopeRepository;
|
||||
|
||||
/// Метод для инициализации репозиториев в приложении
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [onProgress] - обратный вызов при прогрессе
|
||||
/// - [diContainer] - контейнер зависимостей
|
||||
void init({
|
||||
required OnProgress onProgress,
|
||||
required OnError onError,
|
||||
required DiContainer diContainer,
|
||||
}) {
|
||||
try {
|
||||
//Инициализация репозитория авторизации
|
||||
authRepository = _lazyInitRepo<IAuthRepository>(
|
||||
mockFactory: AuthMockRepository.new,
|
||||
mainFactory: () => AuthRepository(
|
||||
httpClient: diContainer.httpClientFactory(
|
||||
diContainer.debugService,
|
||||
diContainer.appConfig,
|
||||
),
|
||||
),
|
||||
onProgress: onProgress,
|
||||
environment: diContainer.env,
|
||||
);
|
||||
onProgress(authRepository.name);
|
||||
} on Object catch (error, stackTrace) {
|
||||
onError(
|
||||
'Ошибка инициализации репозитория IAuthRepository',
|
||||
error,
|
||||
stackTrace,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// Инициализация репозитория сервиса управления токеном доступа
|
||||
mainRepository = _lazyInitRepo<IMainRepository>(
|
||||
mockFactory: MainMockRepository.new,
|
||||
mainFactory: () => MainRepository(
|
||||
httpClient: diContainer.httpClientFactory(
|
||||
diContainer.debugService,
|
||||
diContainer.appConfig,
|
||||
),
|
||||
),
|
||||
onProgress: onProgress,
|
||||
environment: diContainer.env,
|
||||
);
|
||||
onProgress(mainRepository.name);
|
||||
} on Object catch (error, stackTrace) {
|
||||
onError(
|
||||
'Ошибка инициализации репозитория IMainRepository',
|
||||
error,
|
||||
stackTrace,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// Инициализация репозитория профиля
|
||||
profileRepository = _lazyInitRepo<IProfileRepository>(
|
||||
mockFactory: ProfileMockRepository.new,
|
||||
mainFactory: () => ProfileRepository(
|
||||
httpClient: diContainer.httpClientFactory(
|
||||
diContainer.debugService,
|
||||
diContainer.appConfig,
|
||||
),
|
||||
),
|
||||
onProgress: onProgress,
|
||||
environment: diContainer.env,
|
||||
);
|
||||
onProgress(profileRepository.name);
|
||||
} on Object catch (error, stackTrace) {
|
||||
onError(
|
||||
'Ошибка инициализации репозитория IProfileRepository',
|
||||
error,
|
||||
stackTrace,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// Инициализация репозитория профиля scope
|
||||
profileScopeRepository = _lazyInitRepo<IProfileScopeRepository>(
|
||||
mockFactory: ProfileScopeMockRepository.new,
|
||||
mainFactory: () => ProfileScopeRepository(
|
||||
httpClient: diContainer.httpClientFactory(
|
||||
diContainer.debugService,
|
||||
diContainer.appConfig,
|
||||
),
|
||||
),
|
||||
onProgress: onProgress,
|
||||
environment: diContainer.env,
|
||||
);
|
||||
onProgress(mainRepository.name);
|
||||
} on Object catch (error, stackTrace) {
|
||||
onError(
|
||||
'Ошибка инициализации репозитория IProfileScopeRepository',
|
||||
error,
|
||||
stackTrace,
|
||||
);
|
||||
}
|
||||
|
||||
onProgress(
|
||||
'Инициализация репозиториев завершена! Было подменено репозиториев - ${_mockReposToSwitch.length} (${_mockReposToSwitch.join(', ')})',
|
||||
);
|
||||
}
|
||||
|
||||
/// Метод для ленивой инициализации конкретного репозитория по типу [Т].
|
||||
/// В зависимости от окружения инициализируется моковый или сетевой репозиторий.
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [mockFactory] - функция - фабрика для инициализации репозитория для управления моковыми запросами
|
||||
/// - [mainFactory] - функция - фабрика для инициализации основного репозиторий
|
||||
/// - [onProgress] - обратный вызов при прогрессе
|
||||
T _lazyInitRepo<T extends DiBaseRepo>({
|
||||
required AppEnv environment,
|
||||
required T Function() mainFactory,
|
||||
required T Function() mockFactory,
|
||||
required OnProgress onProgress,
|
||||
}) {
|
||||
final mockRepo = mockFactory();
|
||||
final mainRepo = mainFactory();
|
||||
|
||||
final repo = switch (environment) {
|
||||
AppEnv.dev => mockRepo,
|
||||
AppEnv.prod => mainRepo,
|
||||
AppEnv.stage =>
|
||||
_mockReposToSwitch.contains(mockRepo.name) ? mockRepo : mainRepo,
|
||||
};
|
||||
|
||||
onProgress(repo.name);
|
||||
return repo;
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import 'package:app_services/app_services.dart';
|
||||
import 'package:friflex_starter/di/di_container.dart';
|
||||
import 'package:friflex_starter/di/di_typedefs.dart';
|
||||
import 'package:i_app_services/i_app_services.dart';
|
||||
|
||||
/// Класс для инициализации сервисов
|
||||
final class DiServices {
|
||||
/// Сервис для работы с путями
|
||||
late final IPathProvider pathProvider;
|
||||
|
||||
/// Сервис для работы с локальным хранилищем
|
||||
late final ISecureStorage secureStorage;
|
||||
|
||||
/// Метод для инициализации репозиториев в приложении
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [onProgress] - обратный вызов при прогрессе
|
||||
/// - [diContainer] - контейнер зависимостей
|
||||
/// - [onError] - обратный вызов при ошибке
|
||||
void init({
|
||||
required OnProgress onProgress,
|
||||
required OnError onError,
|
||||
required DiContainer diContainer,
|
||||
}) {
|
||||
try {
|
||||
pathProvider = AppPathProvider();
|
||||
onProgress(AppPathProvider.name);
|
||||
} on Object catch (error, stackTrace) {
|
||||
onError(
|
||||
'Ошибка инициализации ${IPathProvider.name}',
|
||||
error,
|
||||
stackTrace,
|
||||
);
|
||||
}
|
||||
try {
|
||||
secureStorage = AppSecureStorage(
|
||||
secretKey: diContainer.appConfig.secretKey,
|
||||
);
|
||||
onProgress(AppSecureStorage.name);
|
||||
} on Object catch (error, stackTrace) {
|
||||
onError(
|
||||
'Ошибка инициализации ${ISecureStorage.name}',
|
||||
error,
|
||||
stackTrace,
|
||||
);
|
||||
}
|
||||
|
||||
onProgress('Инициализация сервисов завершена!');
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
/// Обратный вызов при ошибки инициализации
|
||||
typedef OnError = void Function(
|
||||
String message,
|
||||
Object error, [
|
||||
StackTrace? stackTrace,
|
||||
]);
|
||||
|
||||
/// Обратный вызов при прогрессе
|
||||
typedef OnProgress = void Function(String name);
|
||||
|
||||
/// Обратный вызов при успешной инициализации
|
||||
typedef OnComplete = void Function(String msg);
|
||||
@@ -1,9 +0,0 @@
|
||||
import '../../domain/repository/i_auth_repository.dart';
|
||||
|
||||
/// {@template AuthMockRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
final class AuthMockRepository implements IAuthRepository {
|
||||
@override
|
||||
String get name => 'AuthMockRepository';
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import 'package:friflex_starter/app/http/i_http_client.dart';
|
||||
|
||||
import '../../domain/repository/i_auth_repository.dart';
|
||||
|
||||
/// {@template AuthRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
final class AuthRepository implements IAuthRepository {
|
||||
final IHttpClient httpClient;
|
||||
|
||||
AuthRepository({required this.httpClient});
|
||||
|
||||
@override
|
||||
String get name => 'AuthRepository';
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import 'package:friflex_starter/di/di_base_repo.dart';
|
||||
|
||||
/// {@template IAuthRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
abstract interface class IAuthRepository with DiBaseRepo {}
|
||||
@@ -1,21 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// {@template AuthScreen}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
class AuthScreen extends StatelessWidget {
|
||||
/// {@macro AuthScreen}
|
||||
const AuthScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('AuthScreen'),
|
||||
),
|
||||
body: const Center(
|
||||
child: Text('AuthScreen'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:friflex_starter/features/debug/debug_screen.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
abstract final class DebugRoutes {
|
||||
/// Название роута страницы профиля пользователя
|
||||
static const String debugScreenName = 'debug_screen';
|
||||
|
||||
/// Путь роута страницы профиля пользователя
|
||||
static const String _debugScreenPath = '/debug';
|
||||
|
||||
/// Метод для построения ветки роутов по фиче профиля пользователя
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [routes] - вложенные роуты
|
||||
static StatefulShellBranch buildShellBranch({
|
||||
List<RouteBase> routes = const [],
|
||||
List<NavigatorObserver>? observers,
|
||||
}) =>
|
||||
StatefulShellBranch(
|
||||
initialLocation: _debugScreenPath,
|
||||
observers: observers,
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: _debugScreenPath,
|
||||
name: debugScreenName,
|
||||
builder: (context, state) => const DebugScreen(),
|
||||
routes: routes,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/app/app_context_ext.dart';
|
||||
import 'package:friflex_starter/app/theme/app_colors_scheme.dart';
|
||||
import 'package:friflex_starter/gen/assets.gen.dart';
|
||||
import 'package:friflex_starter/gen/fonts.gen.dart';
|
||||
|
||||
class DebugScreen extends StatelessWidget {
|
||||
const DebugScreen({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Debug Screen')),
|
||||
body: Center(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Text(
|
||||
'Реализация SecureStorage: ${context.di.services.secureStorage.nameImpl}',
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Окружение: ${context.di.appConfig.env.name}',
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
context.theme.changeTheme();
|
||||
},
|
||||
child: const Text('Сменить тему'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ColoredBox(
|
||||
color: context.colors.testColor,
|
||||
child: const SizedBox(height: 100, width: 100),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Текущая тема: ${context.theme.themeMode}',
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Текущий репозиторий: ${context.di.repositories.authRepository.name}',
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
context.localization.changeLocal(
|
||||
const Locale('ru', 'RU'),
|
||||
);
|
||||
},
|
||||
child: const Text('Сменить язык на Rусский'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
context.localization.changeLocal(
|
||||
const Locale('en', 'EN'),
|
||||
);
|
||||
},
|
||||
child: const Text('Сменить язык на Английский'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Тестовое слово montserrat bold: ${context.l10n.helloWorld}',
|
||||
style: TextStyle(
|
||||
color: context.colors.testColor,
|
||||
fontFamily: Assets.fonts.montserratBold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Тестовое слово montserrat medium: ${context.l10n.helloWorld}',
|
||||
style: TextStyle(
|
||||
color: context.colors.testColor,
|
||||
fontFamily: FontFamily.montserrat,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Текущий язык: ${context.l10n.localeName}',
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const Text('Тестовая иконка из assets'),
|
||||
const SizedBox(height: 16),
|
||||
Assets.icons.home.svg(),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
throw Exception(
|
||||
'Тестовая ошибка Exception для отладки FlutterError',
|
||||
);
|
||||
},
|
||||
child: const Text('Вызывать ошибку FlutterError'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
await _callError();
|
||||
},
|
||||
child: const Text('Вызывать ошибку PlatformDispatcher'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
await context.di.debugService.openDebugScreen(context);
|
||||
},
|
||||
child: const Text('Вызывать Экран отладки'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _callError() async {
|
||||
throw Exception('Тестовая ошибка Exception для отладки PlatformDispatcher');
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/features/debug/i_debug_service.dart';
|
||||
|
||||
/// Класс реализации интерфейса Debug сервиса
|
||||
class DebugService implements IDebugService {
|
||||
/// Наименование сервиса
|
||||
static const name = 'DebugService';
|
||||
|
||||
@override
|
||||
void logDebug(Object message, {Object? logLevel, Map<String, dynamic>? args}) {
|
||||
if (kDebugMode) {
|
||||
print('Message: $message');
|
||||
}
|
||||
|
||||
/// Реализация логики
|
||||
}
|
||||
|
||||
@override
|
||||
void logError(
|
||||
Object message, {
|
||||
Object? error,
|
||||
Object? logLevel,
|
||||
Map<String, dynamic>? args,
|
||||
StackTrace? stackTrace,
|
||||
}) {
|
||||
final logMessage = message is Function ? Function.apply(message, []) as Object : message;
|
||||
if (kDebugMode) {
|
||||
print('Message: $logMessage');
|
||||
print('Error: $error');
|
||||
print('StackTrace: $stackTrace');
|
||||
}
|
||||
|
||||
/// Реализация логики
|
||||
}
|
||||
|
||||
@override
|
||||
void log(Object message, {Object? logLevel, Map<String, dynamic>? args}) {
|
||||
final logMessage = message is Function ? Function.apply(message, []) as Object : message;
|
||||
if (kDebugMode) {
|
||||
print('Message: $logMessage');
|
||||
}
|
||||
|
||||
/// Реализация логики
|
||||
}
|
||||
|
||||
@override
|
||||
void logWarning(Object message, {Object? logLevel, Map<String, dynamic>? args}) {
|
||||
final logMessage = message is Function ? Function.apply(message, []) as Object : message;
|
||||
if (kDebugMode) {
|
||||
print('Message: $logMessage');
|
||||
}
|
||||
|
||||
/// Реализация логики
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T?> openDebugScreen<T>(BuildContext context, {bool useRootNavigator = false}) {
|
||||
if (kDebugMode) {
|
||||
print('Переход на страницу отладки');
|
||||
}
|
||||
|
||||
/// Реализация логики
|
||||
return Future.value();
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Интерфейс для сервиса отладки
|
||||
abstract interface class IDebugService {
|
||||
static const name = 'IDebugService';
|
||||
|
||||
/// Метод для логирования сообщений
|
||||
void log(
|
||||
Object message, {
|
||||
Object logLevel,
|
||||
Map<String, dynamic>? args,
|
||||
});
|
||||
|
||||
/// Метод для логирования предупреждений
|
||||
void logWarning(
|
||||
Object message, {
|
||||
Object logLevel,
|
||||
Map<String, dynamic>? args,
|
||||
});
|
||||
|
||||
/// Метод для логирования ошибок
|
||||
void logError(
|
||||
Object message, {
|
||||
Object error,
|
||||
StackTrace? stackTrace,
|
||||
Object logLevel,
|
||||
Map<String, dynamic>? args,
|
||||
});
|
||||
|
||||
/// Метод для обработки ошибок
|
||||
void logDebug(
|
||||
Object message, {
|
||||
Object logLevel,
|
||||
Map<String, dynamic>? args,
|
||||
});
|
||||
|
||||
/// Метод для открытия окна отладки
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [context] - для определения навигатора по нему
|
||||
/// - [useRootNavigator] - при true, открывает окно в корневом навигаторе
|
||||
Future<T?> openDebugScreen<T>(
|
||||
BuildContext context, {
|
||||
bool useRootNavigator = false,
|
||||
});
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// {@template ErrorScreen}
|
||||
/// Экран, когда в приложении произошла фатальная ошибка
|
||||
/// {@endtemplate}
|
||||
class ErrorScreen extends StatelessWidget {
|
||||
/// {@macro ErrorScreen}
|
||||
const ErrorScreen({
|
||||
super.key,
|
||||
required this.error,
|
||||
required this.stackTrace,
|
||||
this.onRetry,
|
||||
});
|
||||
|
||||
final Object? error;
|
||||
final StackTrace? stackTrace;
|
||||
final VoidCallback? onRetry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
body: SafeArea(
|
||||
child: Center(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: onRetry,
|
||||
child: const Text('Перезагрузить приложение'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'''
|
||||
Что-то пошло не так, попробуйте перезагрузить приложение
|
||||
error: $error
|
||||
stackTrace: $stackTrace
|
||||
''',
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import '../../domain/repository/i_main_repository.dart';
|
||||
|
||||
/// {@template MainMockRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
final class MainMockRepository implements IMainRepository {
|
||||
@override
|
||||
String get name => 'MainMockRepository';
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import 'package:friflex_starter/app/http/i_http_client.dart';
|
||||
|
||||
import '../../domain/repository/i_main_repository.dart';
|
||||
|
||||
/// {@template MainRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
final class MainRepository implements IMainRepository {
|
||||
final IHttpClient httpClient;
|
||||
|
||||
MainRepository({required this.httpClient});
|
||||
|
||||
@override
|
||||
String get name => 'MainRepository';
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import 'package:friflex_starter/di/di_base_repo.dart';
|
||||
|
||||
/// {@template IMainRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
abstract interface class IMainRepository with DiBaseRepo{}
|
||||
@@ -1,32 +0,0 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:friflex_starter/features/main/presentation/screens/main_screen.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
abstract final class MainRoutes {
|
||||
/// Название роута главной страницы
|
||||
static const String mainScreenName = 'main_screen';
|
||||
|
||||
/// Путь роута страницы профиля пользователя
|
||||
static const String _mainScreenPath = '/main';
|
||||
|
||||
/// Метод для построения ветки роутов по фиче профиля пользователя
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [routes] - вложенные роуты
|
||||
static StatefulShellBranch buildShellBranch({
|
||||
List<RouteBase> routes = const [],
|
||||
List<NavigatorObserver>? observers,
|
||||
}) =>
|
||||
StatefulShellBranch(
|
||||
initialLocation: _mainScreenPath,
|
||||
observers: observers,
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: _mainScreenPath,
|
||||
name: mainScreenName,
|
||||
builder: (context, state) => const MainScreen(),
|
||||
routes: routes,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class MainScreen extends StatelessWidget {
|
||||
const MainScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Main Screen'),
|
||||
),
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
context.push('/profile');
|
||||
},
|
||||
child: const Text('Открыть профиль'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
context.push('/profile_scope');
|
||||
},
|
||||
child: const Text('Открыть профиль с областью видимости'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import '../../domain/repository/i_profile_repository.dart';
|
||||
|
||||
/// {@template ProfileMockRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
final class ProfileMockRepository implements IProfileRepository {
|
||||
@override
|
||||
String get name => 'ProfileMockRepository';
|
||||
|
||||
@override
|
||||
Future<String> fetchUserProfile(String id) {
|
||||
return Future.value('MOCK Yura Petrov');
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import 'package:friflex_starter/app/http/i_http_client.dart';
|
||||
|
||||
import '../../domain/repository/i_profile_repository.dart';
|
||||
|
||||
/// {@template ProfileRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
final class ProfileRepository implements IProfileRepository {
|
||||
final IHttpClient httpClient;
|
||||
|
||||
ProfileRepository({required this.httpClient});
|
||||
|
||||
@override
|
||||
String get name => 'ProfileRepository';
|
||||
|
||||
@override
|
||||
Future<String> fetchUserProfile(String id) async {
|
||||
// Какой-то запрос к серверу
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
// httpClient.get('https://example.com/profile/$id');
|
||||
|
||||
return 'Yura Petrov';
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:friflex_starter/features/profile/domain/repository/i_profile_repository.dart';
|
||||
|
||||
part 'profile_event.dart';
|
||||
part 'profile_state.dart';
|
||||
|
||||
class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
|
||||
ProfileBloc(this._profileRepository) : super(ProfileInitialState()) {
|
||||
// Вам необходимо добавлять только
|
||||
// один обработчик событий в конструкторе
|
||||
on<ProfileEvent>((event, emit) async {
|
||||
if (event is ProfileFetchProfileEvent) {
|
||||
await _fetchProfile(event, emit);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
final IProfileRepository _profileRepository;
|
||||
|
||||
Future<void> _fetchProfile(
|
||||
ProfileFetchProfileEvent event,
|
||||
Emitter<ProfileState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(ProfileWaitingState());
|
||||
final data = await _profileRepository.fetchUserProfile(event.id);
|
||||
emit(ProfileSuccessState(data: data));
|
||||
} on Object catch (error, stackTrace) {
|
||||
emit(
|
||||
ProfileErrorState(
|
||||
message: 'Ошибка при загрузке профиля',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
part of 'profile_bloc.dart';
|
||||
|
||||
sealed class ProfileEvent extends Equatable {
|
||||
const ProfileEvent();
|
||||
|
||||
@override
|
||||
List<Object> get props => [];
|
||||
}
|
||||
|
||||
final class ProfileFetchProfileEvent extends ProfileEvent {
|
||||
final String id;
|
||||
|
||||
const ProfileFetchProfileEvent({required this.id});
|
||||
|
||||
@override
|
||||
List<Object> get props => [id];
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
part of 'profile_bloc.dart';
|
||||
|
||||
sealed class ProfileState extends Equatable {
|
||||
const ProfileState();
|
||||
|
||||
@override
|
||||
List<Object> get props => [];
|
||||
}
|
||||
|
||||
final class ProfileInitialState extends ProfileState {}
|
||||
|
||||
final class ProfileWaitingState extends ProfileState {}
|
||||
|
||||
final class ProfileErrorState extends ProfileState {
|
||||
final String message;
|
||||
final Object error;
|
||||
final StackTrace? stackTrace;
|
||||
|
||||
const ProfileErrorState({
|
||||
required this.message,
|
||||
required this.error,
|
||||
this.stackTrace,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object> get props => [message, error];
|
||||
}
|
||||
|
||||
final class ProfileSuccessState extends ProfileState {
|
||||
final Object data;
|
||||
|
||||
const ProfileSuccessState({required this.data});
|
||||
|
||||
@override
|
||||
List<Object> get props => [data];
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import 'package:friflex_starter/di/di_base_repo.dart';
|
||||
|
||||
/// {@template IProfileRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
abstract interface class IProfileRepository with DiBaseRepo {
|
||||
Future<String> fetchUserProfile(String id);
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:friflex_starter/app/app_context_ext.dart';
|
||||
import 'package:friflex_starter/features/profile/domain/bloc/profile_bloc.dart';
|
||||
|
||||
// Класс экрана, где мы инициализируем ProfileBloc
|
||||
// и вызываем событие ProfileFetchProfileEvent
|
||||
class ProfileScreen extends StatelessWidget {
|
||||
const ProfileScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final profileRepository = context.di.repositories.profileRepository;
|
||||
// Здесь мы инициализируем ProfileBloc
|
||||
// и вызываем событие ProfileFetchProfileEvent
|
||||
// Или любые другие события, которые вам нужны
|
||||
return BlocProvider(
|
||||
create: (context) => ProfileBloc(profileRepository)
|
||||
..add(const ProfileFetchProfileEvent(id: '1')),
|
||||
child: const _ProfileScreenView(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Виджет, который отображает UI экрана
|
||||
class _ProfileScreenView extends StatelessWidget {
|
||||
const _ProfileScreenView();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Profile'),
|
||||
),
|
||||
body: Center(
|
||||
child: BlocBuilder<ProfileBloc, ProfileState>(
|
||||
builder: (context, state) {
|
||||
return switch (state) {
|
||||
ProfileSuccessState() => Text('Data: ${state.props.first}'),
|
||||
ProfileErrorState() => Text('Error: ${state.message}'),
|
||||
_ => const CircularProgressIndicator(),
|
||||
};
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import '../../domain/repository/i_profile_scope_repository.dart';
|
||||
|
||||
/// {@template ProfileScopeMockRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
final class ProfileScopeMockRepository implements IProfileScopeRepository {
|
||||
@override
|
||||
String get name => 'ProfileScopeMockRepository';
|
||||
|
||||
@override
|
||||
Future<String> fetchUserProfile(String id) async {
|
||||
return 'MOCK Yura Petrov';
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import 'package:friflex_starter/app/http/i_http_client.dart';
|
||||
|
||||
import '../../domain/repository/i_profile_scope_repository.dart';
|
||||
|
||||
/// {@template ProfileScopeRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
final class ProfileScopeRepository implements IProfileScopeRepository {
|
||||
final IHttpClient httpClient;
|
||||
|
||||
ProfileScopeRepository({required this.httpClient});
|
||||
|
||||
@override
|
||||
String get name => 'ProfileScopeRepository';
|
||||
|
||||
@override
|
||||
Future<String> fetchUserProfile(String id) async {
|
||||
// Какой-то запрос к серверу
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
// httpClient.get('https://example.com/profile/$id');
|
||||
|
||||
return 'Yura Petrov';
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:friflex_starter/features/profile_scope/domain/repository/i_profile_scope_repository.dart';
|
||||
|
||||
part 'profile_scope_event.dart';
|
||||
part 'profile_scope_state.dart';
|
||||
|
||||
class ProfileScopeBloc extends Bloc<ProfileScopeEvent, ProfileScopeState> {
|
||||
ProfileScopeBloc({required IProfileScopeRepository profileRepository})
|
||||
: _profileRepository = profileRepository,
|
||||
super(ProfileScopeInitialState()) {
|
||||
// Вам необходимо добавлять только
|
||||
// один обработчик событий в конструкторе
|
||||
on<ProfileScopeEvent>((event, emit) async {
|
||||
return switch (event) {
|
||||
ProfileScopeFetchProfileEvent() => await _fetchProfile(event, emit),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
final IProfileScopeRepository _profileRepository;
|
||||
|
||||
Future<void> _fetchProfile(
|
||||
ProfileScopeFetchProfileEvent event,
|
||||
Emitter<ProfileScopeState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(ProfileScopeWaitingState());
|
||||
final data = await _profileRepository.fetchUserProfile(event.id);
|
||||
emit(ProfileScopeSuccessState(data: data));
|
||||
} on Object catch (error, stackTrace) {
|
||||
emit(
|
||||
ProfileScopeErrorState(
|
||||
message: 'Ошибка при загрузке профиля',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
part of 'profile_scope_bloc.dart';
|
||||
|
||||
sealed class ProfileScopeEvent extends Equatable {
|
||||
const ProfileScopeEvent();
|
||||
|
||||
@override
|
||||
List<Object> get props => [];
|
||||
}
|
||||
|
||||
final class ProfileScopeFetchProfileEvent extends ProfileScopeEvent {
|
||||
final String id;
|
||||
|
||||
const ProfileScopeFetchProfileEvent({required this.id});
|
||||
|
||||
@override
|
||||
List<Object> get props => [id];
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
part of 'profile_scope_bloc.dart';
|
||||
|
||||
sealed class ProfileScopeState extends Equatable {
|
||||
const ProfileScopeState();
|
||||
|
||||
@override
|
||||
List<Object> get props => [];
|
||||
}
|
||||
|
||||
final class ProfileScopeInitialState extends ProfileScopeState {}
|
||||
|
||||
final class ProfileScopeWaitingState extends ProfileScopeState {}
|
||||
|
||||
final class ProfileScopeErrorState extends ProfileScopeState {
|
||||
final String message;
|
||||
final Object error;
|
||||
final StackTrace? stackTrace;
|
||||
|
||||
const ProfileScopeErrorState({
|
||||
required this.message,
|
||||
required this.error,
|
||||
this.stackTrace,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object> get props => [message, error];
|
||||
}
|
||||
|
||||
final class ProfileScopeSuccessState extends ProfileScopeState {
|
||||
final Object data;
|
||||
|
||||
const ProfileScopeSuccessState({required this.data});
|
||||
|
||||
@override
|
||||
List<Object> get props => [data];
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import 'package:friflex_starter/di/di_base_repo.dart';
|
||||
|
||||
/// {@template IProfileScopeRepository}
|
||||
///
|
||||
/// {@endtemplate}
|
||||
abstract interface class IProfileScopeRepository with DiBaseRepo {
|
||||
Future<String> fetchUserProfile(String id);
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/app/app_context_ext.dart';
|
||||
import 'package:friflex_starter/features/profile_scope/domain/bloc/profile_scope_bloc.dart';
|
||||
|
||||
class ProfileInheritedScope extends InheritedWidget {
|
||||
const ProfileInheritedScope({
|
||||
required this.profileScopeBloc,
|
||||
required super.child,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final ProfileScopeBloc profileScopeBloc;
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(ProfileInheritedScope oldWidget) =>
|
||||
profileScopeBloc != oldWidget.profileScopeBloc;
|
||||
}
|
||||
|
||||
class ProfileScope extends StatefulWidget {
|
||||
const ProfileScope({
|
||||
required this.child,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
|
||||
static ProfileInheritedScope? maybeOf(
|
||||
BuildContext context, {
|
||||
bool listen = false,
|
||||
}) {
|
||||
return listen
|
||||
? context.dependOnInheritedWidgetOfExactType<ProfileInheritedScope>()
|
||||
: context.getInheritedWidgetOfExactType<ProfileInheritedScope>();
|
||||
}
|
||||
|
||||
static ProfileInheritedScope of(
|
||||
BuildContext context, {
|
||||
bool listen = false,
|
||||
}) {
|
||||
final result = maybeOf(context, listen: listen);
|
||||
|
||||
if (result == null) {
|
||||
throw StateError(
|
||||
'ProfileScope is not found above widget ${context.widget}',
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _ProfileScopeState();
|
||||
}
|
||||
|
||||
class _ProfileScopeState extends State<ProfileScope> {
|
||||
late final ProfileScopeBloc _profileScopeBloc;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
_profileScopeBloc =
|
||||
ProfileScopeBloc(profileRepository: context.di.repositories.profileScopeRepository);
|
||||
_profileScopeBloc.add(const ProfileScopeFetchProfileEvent(id: '1'));
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_profileScopeBloc.close();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ProfileInheritedScope(profileScopeBloc: _profileScopeBloc, child: widget.child);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:friflex_starter/features/profile_scope/domain/bloc/profile_scope_bloc.dart';
|
||||
import 'package:friflex_starter/features/profile_scope/presentation/profile_scope.dart';
|
||||
|
||||
// Класс экрана, где мы инициализируем ProfileScopeBloc
|
||||
class ProfileScopeScreen extends StatelessWidget {
|
||||
const ProfileScopeScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const ProfileScope(
|
||||
child: _ProfileScopeView(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProfileScopeView extends StatelessWidget {
|
||||
const _ProfileScopeView();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Profile Scope')),
|
||||
body: Center(
|
||||
child: BlocBuilder<ProfileScopeBloc, ProfileScopeState>(
|
||||
bloc: ProfileScope.of(context).profileScopeBloc,
|
||||
builder: (context, state) {
|
||||
return switch (state) {
|
||||
ProfileScopeSuccessState() => Text('Data: ${state.props.first}'),
|
||||
ProfileScopeErrorState() => Text('Error: ${state.message}'),
|
||||
_ => const CircularProgressIndicator(),
|
||||
};
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
/// Класс для реализации корневой страницы приложения
|
||||
class RootScreen extends StatelessWidget {
|
||||
/// Создает корневую страницу приложения
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [navigationShell] - текущая ветка навигации
|
||||
const RootScreen({
|
||||
super.key,
|
||||
required this.navigationShell,
|
||||
});
|
||||
|
||||
/// Текущая ветка навигации
|
||||
final StatefulNavigationShell navigationShell;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: navigationShell,
|
||||
bottomNavigationBar: BottomNavigationBar(
|
||||
items: const <BottomNavigationBarItem>[
|
||||
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
|
||||
BottomNavigationBarItem(icon: Icon(Icons.bug_report), label: 'Debug'),
|
||||
],
|
||||
currentIndex: navigationShell.currentIndex,
|
||||
onTap: navigationShell.goBranch,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:friflex_starter/gen/assets.gen.dart';
|
||||
|
||||
/// {@template SplashScreen}
|
||||
/// Экран загрузки приложения.
|
||||
/// {@endtemplate}
|
||||
class SplashScreen extends StatelessWidget {
|
||||
/// {@macro SplashScreen}
|
||||
const SplashScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Assets.lottie.splash.lottie(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
/// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
/// *****************************************************
|
||||
/// FlutterGen
|
||||
/// *****************************************************
|
||||
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: directives_ordering,unnecessary_import,implicit_dynamic_list_literal,deprecated_member_use
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_svg/flutter_svg.dart' as _svg;
|
||||
import 'package:lottie/lottie.dart' as _lottie;
|
||||
import 'package:vector_graphics/vector_graphics.dart' as _vg;
|
||||
|
||||
class $AssetsFontsGen {
|
||||
const $AssetsFontsGen();
|
||||
|
||||
/// File path: assets/fonts/Montserrat-Bold.ttf
|
||||
String get montserratBold => 'assets/fonts/Montserrat-Bold.ttf';
|
||||
|
||||
/// File path: assets/fonts/Montserrat-ExtraBold.ttf
|
||||
String get montserratExtraBold => 'assets/fonts/Montserrat-ExtraBold.ttf';
|
||||
|
||||
/// File path: assets/fonts/Montserrat-Medium.ttf
|
||||
String get montserratMedium => 'assets/fonts/Montserrat-Medium.ttf';
|
||||
|
||||
/// File path: assets/fonts/Montserrat-Regular.ttf
|
||||
String get montserratRegular => 'assets/fonts/Montserrat-Regular.ttf';
|
||||
|
||||
/// File path: assets/fonts/Montserrat-SemiBold.ttf
|
||||
String get montserratSemiBold => 'assets/fonts/Montserrat-SemiBold.ttf';
|
||||
|
||||
/// List of all assets
|
||||
List<String> get values => [
|
||||
montserratBold,
|
||||
montserratExtraBold,
|
||||
montserratMedium,
|
||||
montserratRegular,
|
||||
montserratSemiBold
|
||||
];
|
||||
}
|
||||
|
||||
class $AssetsIconsGen {
|
||||
const $AssetsIconsGen();
|
||||
|
||||
/// File path: assets/icons/home.svg
|
||||
SvgGenImage get home => const SvgGenImage('assets/icons/home.svg');
|
||||
|
||||
/// List of all assets
|
||||
List<SvgGenImage> get values => [home];
|
||||
}
|
||||
|
||||
class $AssetsLottieGen {
|
||||
const $AssetsLottieGen();
|
||||
|
||||
/// File path: assets/lottie/splash.json
|
||||
LottieGenImage get splash =>
|
||||
const LottieGenImage('assets/lottie/splash.json');
|
||||
|
||||
/// List of all assets
|
||||
List<LottieGenImage> get values => [splash];
|
||||
}
|
||||
|
||||
class Assets {
|
||||
Assets._();
|
||||
|
||||
static const $AssetsFontsGen fonts = $AssetsFontsGen();
|
||||
static const $AssetsIconsGen icons = $AssetsIconsGen();
|
||||
static const $AssetsLottieGen lottie = $AssetsLottieGen();
|
||||
}
|
||||
|
||||
class SvgGenImage {
|
||||
const SvgGenImage(
|
||||
this._assetName, {
|
||||
this.size,
|
||||
this.flavors = const {},
|
||||
}) : _isVecFormat = false;
|
||||
|
||||
const SvgGenImage.vec(
|
||||
this._assetName, {
|
||||
this.size,
|
||||
this.flavors = const {},
|
||||
}) : _isVecFormat = true;
|
||||
|
||||
final String _assetName;
|
||||
final Size? size;
|
||||
final Set<String> flavors;
|
||||
final bool _isVecFormat;
|
||||
|
||||
_svg.SvgPicture svg({
|
||||
Key? key,
|
||||
bool matchTextDirection = false,
|
||||
AssetBundle? bundle,
|
||||
String? package,
|
||||
double? width,
|
||||
double? height,
|
||||
BoxFit fit = BoxFit.contain,
|
||||
AlignmentGeometry alignment = Alignment.center,
|
||||
bool allowDrawingOutsideViewBox = false,
|
||||
WidgetBuilder? placeholderBuilder,
|
||||
String? semanticsLabel,
|
||||
bool excludeFromSemantics = false,
|
||||
_svg.SvgTheme? theme,
|
||||
ColorFilter? colorFilter,
|
||||
Clip clipBehavior = Clip.hardEdge,
|
||||
@deprecated Color? color,
|
||||
@deprecated BlendMode colorBlendMode = BlendMode.srcIn,
|
||||
@deprecated bool cacheColorFilter = false,
|
||||
}) {
|
||||
final _svg.BytesLoader loader;
|
||||
if (_isVecFormat) {
|
||||
loader = _vg.AssetBytesLoader(
|
||||
_assetName,
|
||||
assetBundle: bundle,
|
||||
packageName: package,
|
||||
);
|
||||
} else {
|
||||
loader = _svg.SvgAssetLoader(
|
||||
_assetName,
|
||||
assetBundle: bundle,
|
||||
packageName: package,
|
||||
theme: theme,
|
||||
);
|
||||
}
|
||||
return _svg.SvgPicture(
|
||||
loader,
|
||||
key: key,
|
||||
matchTextDirection: matchTextDirection,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: fit,
|
||||
alignment: alignment,
|
||||
allowDrawingOutsideViewBox: allowDrawingOutsideViewBox,
|
||||
placeholderBuilder: placeholderBuilder,
|
||||
semanticsLabel: semanticsLabel,
|
||||
excludeFromSemantics: excludeFromSemantics,
|
||||
colorFilter: colorFilter ??
|
||||
(color == null ? null : ColorFilter.mode(color, colorBlendMode)),
|
||||
clipBehavior: clipBehavior,
|
||||
cacheColorFilter: cacheColorFilter,
|
||||
);
|
||||
}
|
||||
|
||||
String get path => _assetName;
|
||||
|
||||
String get keyName => _assetName;
|
||||
}
|
||||
|
||||
class LottieGenImage {
|
||||
const LottieGenImage(
|
||||
this._assetName, {
|
||||
this.flavors = const {},
|
||||
});
|
||||
|
||||
final String _assetName;
|
||||
final Set<String> flavors;
|
||||
|
||||
_lottie.LottieBuilder lottie({
|
||||
Animation<double>? controller,
|
||||
bool? animate,
|
||||
_lottie.FrameRate? frameRate,
|
||||
bool? repeat,
|
||||
bool? reverse,
|
||||
_lottie.LottieDelegates? delegates,
|
||||
_lottie.LottieOptions? options,
|
||||
void Function(_lottie.LottieComposition)? onLoaded,
|
||||
_lottie.LottieImageProviderFactory? imageProviderFactory,
|
||||
Key? key,
|
||||
AssetBundle? bundle,
|
||||
Widget Function(
|
||||
BuildContext,
|
||||
Widget,
|
||||
_lottie.LottieComposition?,
|
||||
)? frameBuilder,
|
||||
ImageErrorWidgetBuilder? errorBuilder,
|
||||
double? width,
|
||||
double? height,
|
||||
BoxFit? fit,
|
||||
AlignmentGeometry? alignment,
|
||||
String? package,
|
||||
bool? addRepaintBoundary,
|
||||
FilterQuality? filterQuality,
|
||||
void Function(String)? onWarning,
|
||||
}) {
|
||||
return _lottie.Lottie.asset(
|
||||
_assetName,
|
||||
controller: controller,
|
||||
animate: animate,
|
||||
frameRate: frameRate,
|
||||
repeat: repeat,
|
||||
reverse: reverse,
|
||||
delegates: delegates,
|
||||
options: options,
|
||||
onLoaded: onLoaded,
|
||||
imageProviderFactory: imageProviderFactory,
|
||||
key: key,
|
||||
bundle: bundle,
|
||||
frameBuilder: frameBuilder,
|
||||
errorBuilder: errorBuilder,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: fit,
|
||||
alignment: alignment,
|
||||
package: package,
|
||||
addRepaintBoundary: addRepaintBoundary,
|
||||
filterQuality: filterQuality,
|
||||
onWarning: onWarning,
|
||||
);
|
||||
}
|
||||
|
||||
String get path => _assetName;
|
||||
|
||||
String get keyName => _assetName;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
/// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
/// *****************************************************
|
||||
/// FlutterGen
|
||||
/// *****************************************************
|
||||
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: directives_ordering,unnecessary_import,implicit_dynamic_list_literal,deprecated_member_use
|
||||
|
||||
class FontFamily {
|
||||
FontFamily._();
|
||||
|
||||
/// Font family: Montserrat
|
||||
static const String montserrat = 'Montserrat';
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"helloWorld": "Hello World!",
|
||||
"@helloWorld": {
|
||||
"description": "The conventional newborn programmer greeting"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"helloWorld": "Привет, мир!",
|
||||
"@helloWorld": {
|
||||
"description": "Обычное приветствие новичка-программиста"
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:intl/intl.dart' as intl;
|
||||
|
||||
import 'app_localizations_en.dart';
|
||||
import 'app_localizations_ru.dart';
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
|
||||
/// Callers can lookup localized strings with an instance of AppLocalizations
|
||||
/// returned by `AppLocalizations.of(context)`.
|
||||
///
|
||||
/// Applications need to include `AppLocalizations.delegate()` in their app's
|
||||
/// `localizationDelegates` list, and the locales they support in the app's
|
||||
/// `supportedLocales` list. For example:
|
||||
///
|
||||
/// ```dart
|
||||
/// import 'gen/app_localizations.dart';
|
||||
///
|
||||
/// return MaterialApp(
|
||||
/// localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
/// supportedLocales: AppLocalizations.supportedLocales,
|
||||
/// home: MyApplicationHome(),
|
||||
/// );
|
||||
/// ```
|
||||
///
|
||||
/// ## Update pubspec.yaml
|
||||
///
|
||||
/// Please make sure to update your pubspec.yaml to include the following
|
||||
/// packages:
|
||||
///
|
||||
/// ```yaml
|
||||
/// dependencies:
|
||||
/// # Internationalization support.
|
||||
/// flutter_localizations:
|
||||
/// sdk: flutter
|
||||
/// intl: any # Use the pinned version from flutter_localizations
|
||||
///
|
||||
/// # Rest of dependencies
|
||||
/// ```
|
||||
///
|
||||
/// ## iOS Applications
|
||||
///
|
||||
/// iOS applications define key application metadata, including supported
|
||||
/// locales, in an Info.plist file that is built into the application bundle.
|
||||
/// To configure the locales supported by your app, you’ll need to edit this
|
||||
/// file.
|
||||
///
|
||||
/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file.
|
||||
/// Then, in the Project Navigator, open the Info.plist file under the Runner
|
||||
/// project’s Runner folder.
|
||||
///
|
||||
/// Next, select the Information Property List item, select Add Item from the
|
||||
/// Editor menu, then select Localizations from the pop-up menu.
|
||||
///
|
||||
/// Select and expand the newly-created Localizations item then, for each
|
||||
/// locale your application supports, add a new item and select the locale
|
||||
/// you wish to add from the pop-up menu in the Value field. This list should
|
||||
/// be consistent with the languages listed in the AppLocalizations.supportedLocales
|
||||
/// property.
|
||||
abstract class AppLocalizations {
|
||||
AppLocalizations(String locale) : localeName = intl.Intl.canonicalizedLocale(locale.toString());
|
||||
|
||||
final String localeName;
|
||||
|
||||
static AppLocalizations? of(BuildContext context) {
|
||||
return Localizations.of<AppLocalizations>(context, AppLocalizations);
|
||||
}
|
||||
|
||||
static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();
|
||||
|
||||
/// A list of this localizations delegate along with the default localizations
|
||||
/// delegates.
|
||||
///
|
||||
/// Returns a list of localizations delegates containing this delegate along with
|
||||
/// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
|
||||
/// and GlobalWidgetsLocalizations.delegate.
|
||||
///
|
||||
/// Additional delegates can be added by appending to this list in
|
||||
/// MaterialApp. This list does not have to be used at all if a custom list
|
||||
/// of delegates is preferred or required.
|
||||
static const List<LocalizationsDelegate<dynamic>> localizationsDelegates = <LocalizationsDelegate<dynamic>>[
|
||||
delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
];
|
||||
|
||||
/// A list of this localizations delegate's supported locales.
|
||||
static const List<Locale> supportedLocales = <Locale>[
|
||||
Locale('en'),
|
||||
Locale('ru')
|
||||
];
|
||||
|
||||
/// The conventional newborn programmer greeting
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Hello World!'**
|
||||
String get helloWorld;
|
||||
}
|
||||
|
||||
class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
|
||||
const _AppLocalizationsDelegate();
|
||||
|
||||
@override
|
||||
Future<AppLocalizations> load(Locale locale) {
|
||||
return SynchronousFuture<AppLocalizations>(lookupAppLocalizations(locale));
|
||||
}
|
||||
|
||||
@override
|
||||
bool isSupported(Locale locale) => <String>['en', 'ru'].contains(locale.languageCode);
|
||||
|
||||
@override
|
||||
bool shouldReload(_AppLocalizationsDelegate old) => false;
|
||||
}
|
||||
|
||||
AppLocalizations lookupAppLocalizations(Locale locale) {
|
||||
|
||||
|
||||
// Lookup logic when only language code is specified.
|
||||
switch (locale.languageCode) {
|
||||
case 'en': return AppLocalizationsEn();
|
||||
case 'ru': return AppLocalizationsRu();
|
||||
}
|
||||
|
||||
throw FlutterError(
|
||||
'AppLocalizations.delegate failed to load unsupported locale "$locale". This is likely '
|
||||
'an issue with the localizations generation tool. Please file an issue '
|
||||
'on GitHub with a reproducible sample app and the gen-l10n configuration '
|
||||
'that was used.'
|
||||
);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// ignore: unused_import
|
||||
import 'package:intl/intl.dart' as intl;
|
||||
import 'app_localizations.dart';
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
|
||||
/// The translations for English (`en`).
|
||||
class AppLocalizationsEn extends AppLocalizations {
|
||||
AppLocalizationsEn([String locale = 'en']) : super(locale);
|
||||
|
||||
@override
|
||||
String get helloWorld => 'Hello World!';
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// ignore: unused_import
|
||||
import 'package:intl/intl.dart' as intl;
|
||||
import 'app_localizations.dart';
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
|
||||
/// The translations for Russian (`ru`).
|
||||
class AppLocalizationsRu extends AppLocalizations {
|
||||
AppLocalizationsRu([String locale = 'ru']) : super(locale);
|
||||
|
||||
@override
|
||||
String get helloWorld => 'Привет, мир!';
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
typedef LocalizationBuilder = Widget Function();
|
||||
|
||||
/// Виджет для перестройки виджета в зависимости от локализации
|
||||
class LocalizationConsumer extends StatelessWidget {
|
||||
const LocalizationConsumer({super.key, required this.builder});
|
||||
|
||||
final LocalizationBuilder builder;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Consumer<LocalizationNotifier>(
|
||||
builder: (_, __, ___) {
|
||||
return builder();
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Класс для управления локализацией
|
||||
final class LocalizationNotifier extends ChangeNotifier {
|
||||
Locale _locale = const Locale('en', 'US');
|
||||
|
||||
Locale get locale => _locale;
|
||||
|
||||
void changeLocal(Locale locale) {
|
||||
_locale = locale;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import 'package:friflex_starter/app/app_env.dart';
|
||||
import 'package:friflex_starter/runner/app_runner.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/src/app.dart';
|
||||
|
||||
void main() => AppRunner(AppEnv.prod).run();
|
||||
void main() {
|
||||
runApp(const App());
|
||||
}
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:friflex_starter/features/debug/debug_routes.dart';
|
||||
import 'package:friflex_starter/features/debug/i_debug_service.dart';
|
||||
import 'package:friflex_starter/features/main/presentation/main_routes.dart';
|
||||
import 'package:friflex_starter/features/profile/presentation/screens/profile_screen.dart';
|
||||
import 'package:friflex_starter/features/profile_scope/presentation/screens/profile_scope_screen.dart';
|
||||
import 'package:friflex_starter/features/root/root_screen.dart';
|
||||
import 'package:friflex_starter/features/splash/splash_screen.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
/// Класс, реализующий роутер приложения и все поля классов
|
||||
class AppRouter {
|
||||
/// Конструктор для инициализации роутера
|
||||
const AppRouter();
|
||||
|
||||
/// Ключ для доступа к корневому навигатору приложения
|
||||
static final rootNavigatorKey = GlobalKey<NavigatorState>();
|
||||
|
||||
/// Начальный роут приложения
|
||||
static String get initialLocation => '/debug';
|
||||
|
||||
/// Метод для создания экземпляра GoRouter
|
||||
static GoRouter createRouter(IDebugService debugService) {
|
||||
return GoRouter(
|
||||
navigatorKey: rootNavigatorKey,
|
||||
debugLogDiagnostics: true,
|
||||
initialLocation: initialLocation,
|
||||
routes: [
|
||||
StatefulShellRoute.indexedStack(
|
||||
parentNavigatorKey: rootNavigatorKey,
|
||||
builder: (context, state, navigationShell) =>
|
||||
RootScreen(navigationShell: navigationShell),
|
||||
branches: [
|
||||
MainRoutes.buildShellBranch(),
|
||||
DebugRoutes.buildShellBranch(),
|
||||
],
|
||||
),
|
||||
GoRoute(
|
||||
path: '/splash',
|
||||
builder: (context, state) => const SplashScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/profile',
|
||||
builder: (context, state) => const ProfileScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/profile_scope',
|
||||
builder: (context, state) => const ProfileScopeScreen(),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:friflex_starter/app/app.dart';
|
||||
import 'package:friflex_starter/app/app_env.dart';
|
||||
import 'package:friflex_starter/di/di_container.dart';
|
||||
import 'package:friflex_starter/features/debug/debug_service.dart';
|
||||
import 'package:friflex_starter/features/debug/i_debug_service.dart';
|
||||
import 'package:friflex_starter/features/error/error_screen.dart';
|
||||
import 'package:friflex_starter/router/app_router.dart';
|
||||
import 'package:friflex_starter/runner/timer_runner.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
part 'errors_handlers.dart';
|
||||
|
||||
/// Время ожидания инициализации зависимостей
|
||||
/// Если время превышено, то будет показан экран ошибки
|
||||
/// В дальнейшем нужно убрать в env
|
||||
const _initTimeout = Duration(seconds: 7);
|
||||
|
||||
/// Класс, реализующий раннер для конфигурирования приложения при запуске
|
||||
///
|
||||
/// Порядок инициализации:
|
||||
/// 1. _initApp - инициализация конфигурации приложения
|
||||
/// 2. инициализация репозиториев приложения (будет позже)
|
||||
/// 3. runApp - запуск приложения
|
||||
/// 4. _onAppLoaded - после запуска приложения
|
||||
class AppRunner {
|
||||
/// Создает экземпляр раннера приложения
|
||||
///
|
||||
/// Принимает:
|
||||
/// - [env] - тип окружения сборки приложения
|
||||
AppRunner(this.env);
|
||||
|
||||
/// Тип окружения сборки приложения¬
|
||||
final AppEnv env;
|
||||
|
||||
/// Контейнер зависимостей приложения
|
||||
late IDebugService _debugService;
|
||||
|
||||
/// Роутер приложения
|
||||
late GoRouter router;
|
||||
|
||||
/// Таймер для отслеживания времени инициализации приложения
|
||||
late TimerRunner _timerRunner;
|
||||
|
||||
/// Метод для запуска приложения
|
||||
Future<void> run() async {
|
||||
try {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
// Инициализация сервиса отладки
|
||||
_debugService = DebugService();
|
||||
|
||||
_timerRunner = TimerRunner(_debugService);
|
||||
|
||||
// Инициализация приложения
|
||||
await _initApp();
|
||||
|
||||
// Инициализация метода обработки ошибок
|
||||
_initErrorHandlers(_debugService);
|
||||
|
||||
// Инициализация роутера
|
||||
router = AppRouter.createRouter(_debugService);
|
||||
|
||||
// throw Exception('Test error');
|
||||
|
||||
runApp(
|
||||
App(
|
||||
router: router,
|
||||
initDependencies: () {
|
||||
return _initDependencies(
|
||||
debugService: _debugService,
|
||||
env: env,
|
||||
timerRunner: _timerRunner,
|
||||
).timeout(
|
||||
_initTimeout,
|
||||
onTimeout: () {
|
||||
return Future.error(
|
||||
TimeoutException(
|
||||
'Превышено время ожидания инициализации зависимостей',
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
await _onAppLoaded();
|
||||
} on Object catch (e, stackTrace) {
|
||||
await _onAppLoaded();
|
||||
|
||||
/// Если произошла ошибка при инициализации приложения,
|
||||
/// то запускаем экран ошибки
|
||||
runApp(ErrorScreen(error: e, stackTrace: stackTrace, onRetry: run));
|
||||
}
|
||||
}
|
||||
|
||||
/// Метод инициализации приложения,
|
||||
/// выполняется до запуска приложения
|
||||
Future<void> _initApp() async {
|
||||
// Запрет на поворот экрана
|
||||
await SystemChrome.setPreferredOrientations(
|
||||
[DeviceOrientation.portraitUp],
|
||||
);
|
||||
|
||||
// Заморозка первого кадра (сплеш)
|
||||
WidgetsBinding.instance.deferFirstFrame();
|
||||
}
|
||||
|
||||
/// Метод срабатывает после запуска приложения
|
||||
Future<void> _onAppLoaded() async {
|
||||
// Разморозка первого кадра (сплеш)
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
WidgetsBinding.instance.allowFirstFrame();
|
||||
});
|
||||
}
|
||||
|
||||
// Метод для инициализации зависимостей приложения
|
||||
Future<DiContainer> _initDependencies({
|
||||
required IDebugService debugService,
|
||||
required AppEnv env,
|
||||
required TimerRunner timerRunner,
|
||||
}) async {
|
||||
// Имитация задержки инициализации
|
||||
// TODO(yura): Удалить после проверки
|
||||
await Future.delayed(const Duration(seconds: 3));
|
||||
debugService.log(() => 'Тип сборки: ${env.name}');
|
||||
final diContainer = DiContainer(
|
||||
env: env,
|
||||
dService: debugService,
|
||||
);
|
||||
await diContainer.init(
|
||||
onProgress: (name) => timerRunner.logOnProgress(name),
|
||||
onComplete: (name) {
|
||||
timerRunner
|
||||
..logOnComplete(name)
|
||||
..stop();
|
||||
},
|
||||
onError: (message, error, [stackTrace]) => debugService.logError(
|
||||
message,
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
),
|
||||
);
|
||||
//throw Exception('Test error');
|
||||
return diContainer;
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
part of 'app_runner.dart';
|
||||
|
||||
/// Метод инициализации обработчиков ошибок
|
||||
void _initErrorHandlers(IDebugService debugService) {
|
||||
// Обработка ошибок в приложении
|
||||
FlutterError.onError = (details) {
|
||||
_showErrorScreen(details.exception, details.stack);
|
||||
debugService.logError(
|
||||
() => 'FlutterError.onError: ${details.exceptionAsString()}',
|
||||
error: details.exception,
|
||||
stackTrace: details.stack,
|
||||
);
|
||||
};
|
||||
// Обработка асинхронных ошибок в приложении
|
||||
PlatformDispatcher.instance.onError = (error, stack) {
|
||||
_showErrorScreen(error, stack);
|
||||
debugService.logError(
|
||||
() => 'PlatformDispatcher.instance.onError',
|
||||
error: error,
|
||||
stackTrace: stack,
|
||||
);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
/// Метод для показа экрана ошибки
|
||||
void _showErrorScreen(Object error, StackTrace? stackTrace) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
AppRouter.rootNavigatorKey.currentState?.push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ErrorScreen(error: error, stackTrace: stackTrace),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import 'package:friflex_starter/features/debug/i_debug_service.dart';
|
||||
|
||||
/// {@template TimerRunner}
|
||||
/// Класс для подсчета времени запуска приложения
|
||||
/// {@endtemplate}
|
||||
class TimerRunner {
|
||||
/// {@macro TimerRunner}
|
||||
TimerRunner(this._debugService) {
|
||||
_stopwatch.start();
|
||||
}
|
||||
|
||||
/// Сервис для отладки
|
||||
final IDebugService _debugService;
|
||||
|
||||
/// Секундомер для подсчета времени инициализации
|
||||
final _stopwatch = Stopwatch();
|
||||
|
||||
/// Метод для остановки секундомера и вывода времени
|
||||
/// полной инициализации приложения
|
||||
void stop() {
|
||||
_stopwatch.stop();
|
||||
_debugService.log(
|
||||
'Время инициализации приложения: ${_stopwatch.elapsedMilliseconds} мс',
|
||||
);
|
||||
}
|
||||
|
||||
/// Метод для обработки прогресса инициализации зависимостей
|
||||
void logOnProgress(String name) {
|
||||
_debugService.log(
|
||||
'$name успешная инициализация, прогресс: ${_stopwatch.elapsedMilliseconds} мс',
|
||||
);
|
||||
}
|
||||
|
||||
/// Метод для обработки прогресса инициализации зависимостей
|
||||
void logOnComplete(String message) {
|
||||
_debugService.log(
|
||||
'$message, прогресс: ${_stopwatch.elapsedMilliseconds} мс',
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
/// Метод для обработки прогресса инициализации зависимостей
|
||||
void logOnError(
|
||||
String message,
|
||||
Object error, [
|
||||
StackTrace? stackTrace,
|
||||
]) {
|
||||
_debugService.logError(() => message, error: error, stackTrace: stackTrace);
|
||||
}
|
||||
}
|
||||
75
lib/src/app.dart
Normal file
75
lib/src/app.dart
Normal file
@@ -0,0 +1,75 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/src/initialization/app_initialization_step_label.dart';
|
||||
import 'package:friflex_starter/src/initialization/app_initialization_steps.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_scope.dart';
|
||||
import 'package:friflex_starter/src/router/app_router_delegate.dart';
|
||||
import 'package:friflex_starter/src/splash_screen.dart';
|
||||
|
||||
class App extends StatefulWidget {
|
||||
const App({
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
State<App> createState() => _AppState();
|
||||
}
|
||||
|
||||
class _AppState extends State<App> {
|
||||
late final GlobalKey<NavigatorState> _navigatorKey;
|
||||
late final AppRouterDelegate _routerDelegate;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
_navigatorKey = GlobalKey<NavigatorState>();
|
||||
_routerDelegate = AppRouterDelegate(
|
||||
navigatorKey: _navigatorKey,
|
||||
homePage: const MaterialPage(
|
||||
child: SplashScreen(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_routerDelegate.dispose();
|
||||
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return InitializationScope<AppInitializableStepLabel,
|
||||
AppInitializationStep>(
|
||||
labels: AppInitializableStepLabels.values,
|
||||
// Factory метод для создания объектов для каждого шага
|
||||
// При добавлении новых значений в AppInitializableStepLabels.values, здесь необходимо добавить их обработку
|
||||
createStep: (context, label) {
|
||||
if (label == AppInitializableStepLabels.step0) {
|
||||
return const Step0();
|
||||
} else if (label == AppInitializableStepLabels.step1) {
|
||||
return const Step1();
|
||||
} else if (label == AppInitializableStepLabels.step2) {
|
||||
return const Step2();
|
||||
} else if (label == AppInitializableStepLabels.step3) {
|
||||
return const Step3();
|
||||
} else {
|
||||
throw StateError('Не указан шаг инициализации для "$label"');
|
||||
}
|
||||
},
|
||||
// Здесь описываются взаимосвязи между шагами инициализации для выстраивания корректной последовательности выполнения
|
||||
relations: <AppInitializableStepLabel, Set<AppInitializableStepLabel>>{
|
||||
AppInitializableStepLabels.step3: {
|
||||
AppInitializableStepLabels.step2,
|
||||
},
|
||||
AppInitializableStepLabels.step2: {
|
||||
AppInitializableStepLabels.step1,
|
||||
},
|
||||
},
|
||||
child: MaterialApp.router(
|
||||
routerDelegate: _routerDelegate,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
21
lib/src/initialization/app_initialization_step_label.dart
Normal file
21
lib/src/initialization/app_initialization_step_label.dart
Normal file
@@ -0,0 +1,21 @@
|
||||
import 'package:friflex_starter/src/initialization/initialization_step_label.dart';
|
||||
|
||||
abstract class AppInitializableStepLabels {
|
||||
const AppInitializableStepLabels._();
|
||||
|
||||
static const step0 = AppInitializableStepLabel('step0');
|
||||
static const step1 = AppInitializableStepLabel('step1');
|
||||
static const step2 = AppInitializableStepLabel('step2');
|
||||
static const step3 = AppInitializableStepLabel('step3');
|
||||
|
||||
static Set<AppInitializableStepLabel> values = {
|
||||
step0,
|
||||
step1,
|
||||
step2,
|
||||
step3,
|
||||
};
|
||||
}
|
||||
|
||||
class AppInitializableStepLabel extends InitializableStepLabel<String> {
|
||||
const AppInitializableStepLabel(super.value);
|
||||
}
|
||||
47
lib/src/initialization/app_initialization_steps.dart
Normal file
47
lib/src/initialization/app_initialization_steps.dart
Normal file
@@ -0,0 +1,47 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:friflex_starter/src/initialization/app_initialization_step_label.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_step.dart';
|
||||
|
||||
abstract class AppInitializationStep<R>
|
||||
extends InitializableStep<AppInitializableStepLabel, R> {
|
||||
const AppInitializationStep({
|
||||
required super.label,
|
||||
});
|
||||
}
|
||||
|
||||
class Step0 extends AppInitializationStep<void> {
|
||||
const Step0() : super(label: AppInitializableStepLabels.step0);
|
||||
|
||||
@override
|
||||
FutureOr<void> initialize() async {
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
}
|
||||
}
|
||||
|
||||
class Step1 extends AppInitializationStep<void> {
|
||||
const Step1() : super(label: AppInitializableStepLabels.step1);
|
||||
|
||||
@override
|
||||
FutureOr<void> initialize() async {
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
}
|
||||
}
|
||||
|
||||
class Step2 extends AppInitializationStep<void> {
|
||||
const Step2() : super(label: AppInitializableStepLabels.step2);
|
||||
|
||||
@override
|
||||
FutureOr<void> initialize() async {
|
||||
await Future.delayed(const Duration(seconds: 3));
|
||||
}
|
||||
}
|
||||
|
||||
class Step3 extends AppInitializationStep<void> {
|
||||
const Step3() : super(label: AppInitializableStepLabels.step3);
|
||||
|
||||
@override
|
||||
FutureOr<void> initialize() async {
|
||||
await Future.delayed(const Duration(seconds: 4));
|
||||
}
|
||||
}
|
||||
253
lib/src/initialization/initialization_controller.dart
Normal file
253
lib/src/initialization/initialization_controller.dart
Normal file
@@ -0,0 +1,253 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_step.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_step_label.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_step_result.dart';
|
||||
|
||||
abstract class IInitializationController<L extends InitializableStepLabel,
|
||||
S extends InitializableStep<L, Object?>>
|
||||
implements ValueListenable<InitializationState> {
|
||||
Future<void> initialize(
|
||||
Set<S> steps,
|
||||
Map<L, Set<L>> relations,
|
||||
);
|
||||
}
|
||||
|
||||
class InitializationController<L extends InitializableStepLabel,
|
||||
S extends InitializableStep<L, Object?>>
|
||||
extends ValueNotifier<InitializationState>
|
||||
implements IInitializationController<L, S> {
|
||||
InitializationController() : super(const InitializationState$NotStarted());
|
||||
|
||||
@override
|
||||
Future<void> initialize(
|
||||
Set<S> steps,
|
||||
Map<L, Set<L>> relations,
|
||||
) async {
|
||||
final initializationSw = Stopwatch()..start();
|
||||
final totalSteps = steps.length;
|
||||
var completedStepsCount = 0;
|
||||
try {
|
||||
value = InitializationState$InProgress(
|
||||
completedSteps: completedStepsCount,
|
||||
totalSteps: totalSteps,
|
||||
);
|
||||
final stepsToPerform = <L, S>{};
|
||||
final initialSteps = <S>{};
|
||||
for (final step in steps) {
|
||||
stepsToPerform[step.label] = step;
|
||||
|
||||
final stepDependencies = relations[step.label];
|
||||
if (stepDependencies == null || stepDependencies.isEmpty) {
|
||||
initialSteps.add(step);
|
||||
}
|
||||
}
|
||||
if (initialSteps.isEmpty) {
|
||||
initializationSw.stop();
|
||||
Error.throwWithStackTrace(
|
||||
StateError(
|
||||
'Не найден ни один шаг без зависимостей, нет точки входа для инициализации',
|
||||
),
|
||||
StackTrace.current,
|
||||
);
|
||||
}
|
||||
|
||||
final initializedStepsLabels = <L>{};
|
||||
final notInitializedStepsLabels = <L>{...stepsToPerform.keys};
|
||||
final results = <L, InitializationStepResult<Object?, L, S>>{
|
||||
for (final entry in stepsToPerform.entries)
|
||||
entry.key: InitializationStepResult$NotInitialized(step: entry.value),
|
||||
};
|
||||
|
||||
Future<void> handleSteps(Set<S> stepsToHandle) {
|
||||
print(
|
||||
stepsToHandle.length == 1
|
||||
? 'PERFORMING EXACT STEP ${stepsToHandle.first.runtimeType}'
|
||||
: 'PERFORMING STEPS ${stepsToHandle.map((s) => s.runtimeType)}',
|
||||
);
|
||||
|
||||
return Future.wait(
|
||||
stepsToHandle.map((step) async {
|
||||
final sw = Stopwatch()..start();
|
||||
results[step.label] =
|
||||
InitializationStepResult$InProgress(step: step);
|
||||
|
||||
try {
|
||||
final rawResult = await step.initialize();
|
||||
results[step.label] = InitializationStepResult$Completed(
|
||||
result: rawResult,
|
||||
step: step,
|
||||
);
|
||||
completedStepsCount += 1;
|
||||
final currentValue = value;
|
||||
switch (currentValue) {
|
||||
case InitializationState$Completed():
|
||||
// потенциально невозможный кейс
|
||||
break;
|
||||
case InitializationState$NotStarted():
|
||||
case InitializationState$InProgress():
|
||||
value = InitializationState$InProgress(
|
||||
completedSteps: completedStepsCount,
|
||||
totalSteps: totalSteps,
|
||||
);
|
||||
break;
|
||||
case InitializationState$Failed():
|
||||
value = InitializationState$Failed(
|
||||
completedSteps: completedStepsCount,
|
||||
totalSteps: totalSteps,
|
||||
);
|
||||
}
|
||||
|
||||
print('STEP COMPLETED ${step.runtimeType}');
|
||||
|
||||
initializedStepsLabels.add(step.label);
|
||||
notInitializedStepsLabels.remove(step.label);
|
||||
|
||||
if (notInitializedStepsLabels.isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
final nextStepsToInitialize = <S>{};
|
||||
for (final notInitializedStepLabel in notInitializedStepsLabels) {
|
||||
final stepRelationsLabels = relations[notInitializedStepLabel];
|
||||
if (stepRelationsLabels == null ||
|
||||
stepRelationsLabels.isEmpty) {
|
||||
if (results[notInitializedStepLabel]
|
||||
is InitializationStepResult$NotInitialized) {
|
||||
// TODO bang
|
||||
nextStepsToInitialize.add(
|
||||
stepsToPerform[notInitializedStepLabel]!,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
var hasUninitializedRelation = false;
|
||||
for (final stepRelationLabel in stepRelationsLabels) {
|
||||
if (notInitializedStepsLabels.contains(stepRelationLabel)) {
|
||||
hasUninitializedRelation = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!hasUninitializedRelation &&
|
||||
results[notInitializedStepLabel]
|
||||
is InitializationStepResult$NotInitialized) {
|
||||
// TODO bang
|
||||
nextStepsToInitialize.add(
|
||||
stepsToPerform[notInitializedStepLabel]!,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO сюда sw для подсчета времени инициализации конкретного шага
|
||||
if (nextStepsToInitialize.isNotEmpty) {
|
||||
await handleSteps(nextStepsToInitialize);
|
||||
}
|
||||
} on Object catch (e, s) {
|
||||
sw.stop();
|
||||
results[step.label] = InitializationStepResult$Failed(
|
||||
e: e,
|
||||
s: s,
|
||||
completionTimeInMicroseconds: sw.elapsedMicroseconds,
|
||||
step: step,
|
||||
);
|
||||
print('STEP FAILED ${step.runtimeType}');
|
||||
rethrow;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
await handleSteps(initialSteps);
|
||||
initializationSw.stop();
|
||||
if (completedStepsCount != totalSteps) {
|
||||
Error.throwWithStackTrace(
|
||||
StateError(
|
||||
'Какой-то из шагов инициализации был завершён с ошибкой',
|
||||
),
|
||||
StackTrace.current,
|
||||
);
|
||||
}
|
||||
print(
|
||||
'INITIALIZATION COMPLETED (${initializationSw.elapsedMilliseconds} ms)',
|
||||
);
|
||||
value = InitializationState$Completed(
|
||||
completionTime: Duration(
|
||||
milliseconds: initializationSw.elapsedMilliseconds,
|
||||
),
|
||||
);
|
||||
} on Object catch (e, s) {
|
||||
print(
|
||||
'INITIALIZATION FAILED ($completedStepsCount/$totalSteps | ${initializationSw.elapsedMilliseconds} ms)',
|
||||
);
|
||||
value = InitializationState$Failed(
|
||||
completedSteps: completedStepsCount,
|
||||
totalSteps: totalSteps,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@immutable
|
||||
sealed class InitializationState with EquatableMixin {
|
||||
const InitializationState();
|
||||
|
||||
@override
|
||||
@mustCallSuper
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class InitializationState$NotStarted extends InitializationState {
|
||||
const InitializationState$NotStarted();
|
||||
}
|
||||
|
||||
class InitializationState$InProgress extends InitializationState {
|
||||
const InitializationState$InProgress({
|
||||
required this.completedSteps,
|
||||
required this.totalSteps,
|
||||
});
|
||||
|
||||
final int completedSteps;
|
||||
final int totalSteps;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
completedSteps,
|
||||
totalSteps,
|
||||
super.props,
|
||||
];
|
||||
}
|
||||
|
||||
class InitializationState$Completed extends InitializationState {
|
||||
const InitializationState$Completed({
|
||||
required this.completionTime,
|
||||
});
|
||||
|
||||
final Duration completionTime;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
completionTime,
|
||||
super.props,
|
||||
];
|
||||
}
|
||||
|
||||
class InitializationState$Failed extends InitializationState {
|
||||
const InitializationState$Failed({
|
||||
required this.completedSteps,
|
||||
required this.totalSteps,
|
||||
});
|
||||
|
||||
final int completedSteps;
|
||||
final int totalSteps;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
completedSteps,
|
||||
totalSteps,
|
||||
super.props,
|
||||
];
|
||||
}
|
||||
97
lib/src/initialization/initialization_scope.dart
Normal file
97
lib/src/initialization/initialization_scope.dart
Normal file
@@ -0,0 +1,97 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_controller.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_step.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_step_label.dart';
|
||||
|
||||
class InitializationScope<L extends InitializableStepLabel,
|
||||
S extends InitializableStep<L, Object?>> extends StatefulWidget {
|
||||
const InitializationScope({
|
||||
required this.labels,
|
||||
required this.createStep,
|
||||
required this.relations,
|
||||
required this.child,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final Set<L> labels;
|
||||
final S? Function(BuildContext context, L label) createStep;
|
||||
final Map<L, Set<L>> relations;
|
||||
final Widget child;
|
||||
|
||||
static InitializationInheritedScope of(
|
||||
BuildContext context, {
|
||||
bool listen = false,
|
||||
}) {
|
||||
// TODO bang
|
||||
return _maybeOf(context, listen: listen)!;
|
||||
}
|
||||
|
||||
static InitializationInheritedScope? _maybeOf(
|
||||
BuildContext context, {
|
||||
bool listen = false,
|
||||
}) {
|
||||
return listen
|
||||
? context
|
||||
.dependOnInheritedWidgetOfExactType<InitializationInheritedScope>()
|
||||
: context.getInheritedWidgetOfExactType<InitializationInheritedScope>();
|
||||
}
|
||||
|
||||
@override
|
||||
State<InitializationScope<L, S>> createState() =>
|
||||
_InitializationScopeState<L, S>();
|
||||
}
|
||||
|
||||
class _InitializationScopeState<L extends InitializableStepLabel,
|
||||
S extends InitializableStep<L, Object?>>
|
||||
extends State<InitializationScope<L, S>> {
|
||||
late final InitializationController<L, S> _initializationController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
final labelsWithSteps = <L, S>{};
|
||||
for (final label in widget.labels) {
|
||||
final createdStep = widget.createStep(context, label);
|
||||
if (createdStep == null) continue;
|
||||
labelsWithSteps[label] = createdStep;
|
||||
}
|
||||
|
||||
_initializationController = InitializationController()
|
||||
..initialize(
|
||||
labelsWithSteps.values.toSet(),
|
||||
widget.relations,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_initializationController.dispose();
|
||||
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return InitializationInheritedScope(
|
||||
controller: _initializationController,
|
||||
child: widget.child,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class InitializationInheritedScope extends InheritedWidget {
|
||||
const InitializationInheritedScope({
|
||||
required this.controller,
|
||||
required super.child,
|
||||
super.key,
|
||||
});
|
||||
|
||||
final IInitializationController controller;
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(covariant InheritedWidget oldWidget) {
|
||||
return oldWidget is InitializationInheritedScope &&
|
||||
oldWidget.controller != controller;
|
||||
}
|
||||
}
|
||||
13
lib/src/initialization/initialization_step.dart
Normal file
13
lib/src/initialization/initialization_step.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:friflex_starter/src/initialization/initialization_step_label.dart';
|
||||
|
||||
abstract class InitializableStep<L extends InitializableStepLabel, T> {
|
||||
const InitializableStep({
|
||||
required this.label,
|
||||
});
|
||||
|
||||
final L label;
|
||||
|
||||
FutureOr<T> initialize();
|
||||
}
|
||||
13
lib/src/initialization/initialization_step_label.dart
Normal file
13
lib/src/initialization/initialization_step_label.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
@immutable
|
||||
abstract class InitializableStepLabel<T> with EquatableMixin {
|
||||
final T value;
|
||||
|
||||
const InitializableStepLabel(this.value);
|
||||
|
||||
@override
|
||||
@mustCallSuper
|
||||
List<Object?> get props => [value];
|
||||
}
|
||||
74
lib/src/initialization/initialization_step_result.dart
Normal file
74
lib/src/initialization/initialization_step_result.dart
Normal file
@@ -0,0 +1,74 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_step.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_step_label.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
@immutable
|
||||
sealed class InitializationStepResult<R, L extends InitializableStepLabel,
|
||||
S extends InitializableStep<L, R>> with EquatableMixin {
|
||||
const InitializationStepResult({
|
||||
required this.step,
|
||||
});
|
||||
|
||||
final S step;
|
||||
|
||||
@override
|
||||
@mustCallSuper
|
||||
List<Object?> get props => [step];
|
||||
}
|
||||
|
||||
class InitializationStepResult$NotInitialized<R,
|
||||
L extends InitializableStepLabel, S extends InitializableStep<L, R>>
|
||||
extends InitializationStepResult<R, L, S> {
|
||||
const InitializationStepResult$NotInitialized({
|
||||
required super.step,
|
||||
});
|
||||
}
|
||||
|
||||
class InitializationStepResult$InProgress<R, L extends InitializableStepLabel,
|
||||
S extends InitializableStep<L, R>>
|
||||
extends InitializationStepResult<R, L, S> {
|
||||
const InitializationStepResult$InProgress({
|
||||
required super.step,
|
||||
});
|
||||
}
|
||||
|
||||
class InitializationStepResult$Completed<R, L extends InitializableStepLabel,
|
||||
S extends InitializableStep<L, R>>
|
||||
extends InitializationStepResult<R, L, S> {
|
||||
const InitializationStepResult$Completed({
|
||||
required this.result,
|
||||
required super.step,
|
||||
});
|
||||
|
||||
final R result;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
result,
|
||||
super.props,
|
||||
];
|
||||
}
|
||||
|
||||
class InitializationStepResult$Failed<R, L extends InitializableStepLabel,
|
||||
S extends InitializableStep<L, R>>
|
||||
extends InitializationStepResult<R, L, S> {
|
||||
const InitializationStepResult$Failed({
|
||||
required this.e,
|
||||
required this.s,
|
||||
required this.completionTimeInMicroseconds,
|
||||
required super.step,
|
||||
});
|
||||
|
||||
final Object e;
|
||||
final StackTrace s;
|
||||
final int completionTimeInMicroseconds;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
e,
|
||||
s,
|
||||
completionTimeInMicroseconds,
|
||||
super.props,
|
||||
];
|
||||
}
|
||||
38
lib/src/router/app_router_delegate.dart
Normal file
38
lib/src/router/app_router_delegate.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AppRouterDelegate extends RouterDelegate<String>
|
||||
with ChangeNotifier, PopNavigatorRouterDelegateMixin {
|
||||
AppRouterDelegate({
|
||||
required GlobalKey<NavigatorState> navigatorKey,
|
||||
required Page homePage,
|
||||
}) : _navigatorKey = navigatorKey,
|
||||
_pages = [homePage];
|
||||
|
||||
final GlobalKey<NavigatorState> _navigatorKey;
|
||||
|
||||
late List<Page> _pages;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Navigator(
|
||||
key: navigatorKey,
|
||||
restorationScopeId: 'rootNav',
|
||||
pages: _pages,
|
||||
onDidRemovePage: (page) {
|
||||
_pages = [..._pages]..remove(page);
|
||||
if (_pages.remove(page)) {
|
||||
notifyListeners();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
GlobalKey<NavigatorState>? get navigatorKey => _navigatorKey;
|
||||
|
||||
@override
|
||||
Future<void> setNewRoutePath(String configuration) {
|
||||
return SynchronousFuture(null);
|
||||
}
|
||||
}
|
||||
59
lib/src/splash_screen.dart
Normal file
59
lib/src/splash_screen.dart
Normal file
@@ -0,0 +1,59 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_controller.dart';
|
||||
import 'package:friflex_starter/src/initialization/initialization_scope.dart';
|
||||
|
||||
class SplashScreen extends StatefulWidget {
|
||||
const SplashScreen({
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
State<SplashScreen> createState() => _SplashScreenState();
|
||||
}
|
||||
|
||||
class _SplashScreenState extends State<SplashScreen> {
|
||||
late final IInitializationController _initializationController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
_initializationController = InitializationScope.of(context).controller;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: Center(
|
||||
child: ValueListenableBuilder(
|
||||
valueListenable: _initializationController,
|
||||
builder: (context, state, _) {
|
||||
final String displayedText;
|
||||
switch (state) {
|
||||
case InitializationState$NotStarted():
|
||||
displayedText = 'Инициализация не начата';
|
||||
break;
|
||||
case InitializationState$InProgress():
|
||||
displayedText =
|
||||
'Загружаем ${((state.completedSteps / state.totalSteps) * 100).toInt()}%';
|
||||
break;
|
||||
case InitializationState$Completed():
|
||||
final seconds = state.completionTime.inSeconds;
|
||||
displayedText =
|
||||
'Загрузка завершена (${seconds > 0 ? '$seconds сек. ${state.completionTime.inMilliseconds % Duration.millisecondsPerSecond} мс' : '${state.completionTime.inMilliseconds} мс'} )';
|
||||
break;
|
||||
case InitializationState$Failed():
|
||||
displayedText =
|
||||
'Ошибка загрузки (${state.completedSteps}/${state.totalSteps})';
|
||||
break;
|
||||
}
|
||||
|
||||
return Text(displayedText);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
import 'package:friflex_starter/app/app_env.dart';
|
||||
import 'package:friflex_starter/runner/app_runner.dart';
|
||||
|
||||
void main() => AppRunner(AppEnv.dev).run();
|
||||
@@ -1,5 +0,0 @@
|
||||
|
||||
import 'package:friflex_starter/app/app_env.dart';
|
||||
import 'package:friflex_starter/runner/app_runner.dart';
|
||||
|
||||
void main() => AppRunner(AppEnv.prod).run();
|
||||
@@ -1,5 +0,0 @@
|
||||
|
||||
import 'package:friflex_starter/app/app_env.dart';
|
||||
import 'package:friflex_starter/runner/app_runner.dart';
|
||||
|
||||
void main() => AppRunner(AppEnv.stage).run();
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user