diff --git a/Makefile b/Makefile index f554460b..ba80b922 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,13 @@ -build: - @flutter clean - @flutter build macos --release +build_macos: + @rm -rf release + fvm flutter clean + fvm flutter build macos --release @mkdir release @appdmg installers/dmg_creator/config.json release/Onix_Flutter_Project_Generator.dmg + +build_runner: + fvm dart run build_runner build --delete-conflicting-outputs + +codegen: + dart run build_runner build --delete-conflicting-outputs \ No newline at end of file diff --git a/README.md b/README.md index 908e0ed0..df2c6a56 100644 --- a/README.md +++ b/README.md @@ -18,11 +18,16 @@
How does it work? Watch the video!
+
+ +https://github.com/user-attachments/assets/5fd10595-2964-4006-8926-4715e1032cba +
refine logo +

@@ -77,7 +82,7 @@ Also there an option to select **optional packages to include** to the project: * **Localization** - [Intl](https://pub.dev/packages/intl_utils) * **Theming** - [ThemeTailor](https://pub.dev/packages/theme_tailor) * **UI** - [ScreenUtil](https://pub.dev/packages/flutter_screenutil) - +* **Monitor and capture errors** - [Sentry](https://pub.dev/packages/sentry_flutter) ## Key Features @@ -108,4 +113,4 @@ If you have any doubts related to the project or want to discuss something, then ## License -Licensed under the MIT License, Copyright (c) 2023-present Onix-Systems \ No newline at end of file +Licensed under the MIT License, Copyright (c) 2024-present Onix-Systems diff --git a/analysis_options.yaml b/analysis_options.yaml index c2fdba0c..65f9f11a 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -14,22 +14,253 @@ analyzer: - "bricks/**" - '**/*.g.dart' - '**/*.freezed.dart' + - "lib/app/localization/**" + + errors: + prefer_mixin: ignore + flutter_style_todos: ignore + invalid_annotation_target: ignore + always_use_package_imports: warning + avoid_dynamic_calls: info + avoid_empty_else: error + avoid_print: warning + avoid_relative_lib_imports: warning + avoid_returning_null_for_future: error + avoid_slow_async_io: warning + avoid_type_to_string: error + avoid_types_as_parameter_names: info + avoid_web_libraries_in_flutter: error + cancel_subscriptions: error + close_sinks: error + comment_references: info + control_flow_in_finally: error + empty_statements: error + hash_and_equals: error + iterable_contains_unrelated_type: error + list_remove_unrelated_type: error + literal_only_boolean_expressions: warning + no_adjacent_strings_in_list: error + no_duplicate_case_values: error + no_logic_in_create_state: error + prefer_void_to_null: error + test_types_in_equals: error + throw_in_finally: error + unnecessary_statements: error + unrelated_type_equality_checks: error + unsafe_html: error + use_build_context_synchronously: info + use_key_in_widget_constructors: info + valid_regexps: error + missing_required_param: error + missing_return: error + collection_methods_unrelated_type: warning + avoid_final_parameters: error + cast_nullable_to_non_nullable: warning + implicit_call_tearoffs: info linter: - # The lint rules applied to this project can be customized in the - # section below to disable rules from the `package:flutter_lints/flutter.yaml` - # included above or to enable additional rules. A list of all available lints - # and their documentation is published at - # https://dart-lang.github.io/linter/lints/index.html. - # - # Instead of disabling a lint rule for the entire project in the - # section below, it can also be suppressed for a single line of code - # or a specific dart file by using the `// ignore: name_of_lint` and - # `// ignore_for_file: name_of_lint` syntax on the line or in the file - # producing the lint. rules: - # avoid_print: false # Uncomment to disable the `avoid_print` rule - # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + # Const rules. + prefer_const_constructors: true + prefer_const_constructors_in_immutables: true + prefer_const_declarations: true + prefer_const_literals_to_create_immutables: true + unnecessary_const: true + unnecessary_late: true + + # Error rules. + always_use_package_imports: true + avoid_empty_else: true + avoid_print: true + avoid_relative_lib_imports: true + avoid_slow_async_io: true + avoid_type_to_string: true + avoid_types_as_parameter_names: true + avoid_web_libraries_in_flutter: true + cancel_subscriptions: true + close_sinks: true + control_flow_in_finally: true + empty_statements: true + hash_and_equals: true + collection_methods_unrelated_type: true + literal_only_boolean_expressions: true + no_adjacent_strings_in_list: true + no_duplicate_case_values: true + no_logic_in_create_state: true + prefer_void_to_null: true + test_types_in_equals: true + throw_in_finally: true + unnecessary_statements: true + unrelated_type_equality_checks: true + unsafe_html: true + use_build_context_synchronously: true + use_key_in_widget_constructors: true + valid_regexps: true + avoid_dynamic_calls: true + invalid_case_patterns: true + + # Style rules. + always_declare_return_types: true + always_put_required_named_parameters_first: true + annotate_overrides: true + avoid_annotating_with_dynamic: true + avoid_bool_literals_in_conditional_expressions: true + avoid_catching_errors: true + avoid_equals_and_hash_code_on_mutable_classes: true + avoid_escaping_inner_quotes: true + avoid_field_initializers_in_const_classes: true + avoid_function_literals_in_foreach_calls: true + avoid_implementing_value_types: true + avoid_init_to_null: true + avoid_js_rounded_ints: true + avoid_multiple_declarations_per_line: true + avoid_null_checks_in_equality_operators: true + avoid_positional_boolean_parameters: true + avoid_private_typedef_functions: true + avoid_renaming_method_parameters: true + avoid_return_types_on_setters: true + avoid_returning_null_for_void: true + avoid_returning_this: true + avoid_setters_without_getters: true + avoid_shadowing_type_parameters: true + avoid_single_cascade_in_expression_statements: true + avoid_types_on_closure_parameters: true + avoid_unnecessary_containers: true + avoid_unused_constructor_parameters: true + avoid_void_async: true + await_only_futures: true + camel_case_extensions: true + camel_case_types: true + cascade_invocations: true + constant_identifier_names: true + curly_braces_in_flow_control_structures: true + deprecated_consistency: true + directives_ordering: true + do_not_use_environment: true + empty_catches: true + empty_constructor_bodies: true + exhaustive_cases: true + file_names: true + implementation_imports: true + leading_newlines_in_multiline_strings: true + library_names: true + library_prefixes: true + missing_whitespace_between_adjacent_strings: true + no_runtimeType_toString: true + non_constant_identifier_names: true + null_closures: true + omit_local_variable_types: true + one_member_abstracts: true + only_throw_errors: true + overridden_fields: true + package_api_docs: true + parameter_assignments: true + prefer_adjacent_string_concatenation: true + prefer_asserts_in_initializer_lists: true + prefer_collection_literals: true + prefer_conditional_assignment: true + prefer_constructors_over_static_methods: true + prefer_contains: true + prefer_final_fields: true + prefer_final_in_for_each: true + prefer_final_locals: true + prefer_for_elements_to_map_fromIterable: true + prefer_function_declarations_over_variables: true + prefer_generic_function_type_aliases: true + prefer_if_elements_to_conditional_expressions: true + prefer_if_null_operators: true + prefer_initializing_formals: true + prefer_inlined_adds: true + prefer_interpolation_to_compose_strings: true + prefer_is_empty: true + prefer_is_not_empty: true + prefer_is_not_operator: true + prefer_iterable_whereType: true + prefer_mixin: true + prefer_null_aware_operators: true + prefer_single_quotes: true + prefer_spread_collections: true + prefer_typing_uninitialized_variables: true + provide_deprecation_message: true + public_member_api_docs: false + recursive_getters: true + sized_box_for_whitespace: true + slash_for_doc_comments: true + sort_child_properties_last: true + sort_constructors_first: false + sort_unnamed_constructors_first: false + type_annotate_public_apis: true + type_init_formals: true + unawaited_futures: true + unnecessary_await_in_return: true + unnecessary_brace_in_string_interps: true + unnecessary_getters_setters: true + unnecessary_lambdas: true + unnecessary_new: true + unnecessary_null_aware_assignments: true + unnecessary_null_checks: true + unnecessary_null_in_if_null_operators: true + unnecessary_nullable_for_final_variable_declarations: true + unnecessary_overrides: true + unnecessary_parenthesis: true + unnecessary_raw_strings: true + unnecessary_string_escapes: true + unnecessary_string_interpolations: true + unnecessary_this: true + use_full_hex_values_for_flutter_colors: true + use_function_type_syntax_for_parameters: true + use_if_null_to_convert_nulls_to_bools: true + use_is_even_rather_than_modulo: true + use_late_for_private_fields_and_variables: true + use_named_constants: true + use_raw_strings: true + use_rethrow_when_possible: true + use_setters_to_change_properties: true + use_string_buffers: true + use_to_and_as_if_applicable: true + void_checks: true + lines_longer_than_80_chars: true + flutter_style_todos: true + conditional_uri_does_not_exist: true + no_leading_underscores_for_library_prefixes: true + no_leading_underscores_for_local_identifiers: true + secure_pubspec_urls: true + sized_box_shrink_expand: true + use_decorated_box: true + use_colored_box: true + avoid_double_and_int_checks: true + avoid_final_parameters: true + avoid_redundant_argument_values: true + cast_nullable_to_non_nullable: true + combinators_ordering: true + dangling_library_doc_comments: true + eol_at_end_of_file: true + implicit_call_tearoffs: true + join_return_with_assignment: true + library_private_types_in_public_api: true + no_default_cases: true + noop_primitive_operations: true + null_check_on_nullable_type_parameter: true + package_prefixed_library_names: true + prefer_asserts_with_message: true + prefer_int_literals: true + prefer_null_aware_method_calls: true + require_trailing_commas: true + tighten_type_of_initializing_formals: true + unnecessary_constructor_name: true + unnecessary_library_directive: true + unnecessary_to_list_in_spreads: true + use_enums: true + use_string_in_part_of_directives: true + use_super_parameters: true + use_test_throws_matchers: true + unnecessary_breaks: true + + # Pub rules. + package_names: true + depend_on_referenced_packages: true -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options +#https://github.com/dart-lang/lints/blob/main/lib/core.yaml +#https://github.com/dart-lang/lints/blob/main/lib/recommended.yaml +#https://github.com/flutter/packages/blob/master/packages/flutter_lints/lib/flutter.yaml +#https://pub.dev/packages/dart_code_metrics \ No newline at end of file diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/.env b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/.env index 27cf2606..613ed02b 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/.env +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/.env @@ -1,2 +1,2 @@ -APIKEY1 = 'APIKEY1' -APIKEY2 = 'APIKEY2' \ No newline at end of file +APIKEY1=APIKEY1 +APIKEY2=APIKEY2 \ No newline at end of file diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app.gen.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app.gen.dart index c6f7ccde..5df303e4 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app.gen.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app.gen.dart @@ -3,9 +3,8 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; {{^web_only}}import 'package:loader_overlay/loader_overlay.dart';{{/web_only}} {{#screen_util}}import 'package:flutter_screenutil/flutter_screenutil.dart';{{/screen_util}} -import 'package:{{project_name}}/core/arch/bloc/base_bloc_state.dart'; -import 'package:{{project_name}}/app/bloc/app_bloc_imports.dart'; import 'package:{{project_name}}/presentation/style/theme/theme_imports.dart'; +import 'package:{{project_name}}/core/arch/widget/common/theme_switcher.dart'; {{#isGoRouter}}import 'package:{{project_name}}/app/router/app_router.dart';{{/isGoRouter}} {{^isGoRouter}}import 'package:{{project_name}}/core/di/app.dart';{{/isGoRouter}} {{^handLocalization}}import 'package:flutter_localizations/flutter_localizations.dart';{{/handLocalization}} @@ -13,6 +12,7 @@ import 'package:{{project_name}}/presentation/style/theme/theme_imports.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart';{{/handLocalization}} {{#flavorizr}}import 'package:{{project_name}}/core/arch/widget/common/flavor_banner.dart';{{/flavorizr}} {{^handLocalization}}import 'package:{{project_name}}/app/localization/generated/l10n.dart';{{/handLocalization}} +{{^isGoRouter}}{{#sentry}}import 'package:sentry_flutter/sentry_flutter.dart';{{/sentry}}{{/isGoRouter}} class App extends StatefulWidget { const App({super.key}); @@ -21,12 +21,11 @@ class App extends StatefulWidget { State createState() => _AppState(); } -class _AppState extends BaseState { +class _AppState extends State { Locale? locale; - @override - Widget buildWidget(BuildContext context) { + Widget build(BuildContext context) { {{#isGoRouter}}AppRouter.init();{{/isGoRouter}} return {{^web_only}}GlobalLoaderOverlay( overlayColor: Colors.black.withOpacity(0.5), @@ -35,8 +34,9 @@ class _AppState extends BaseState { designSize: const Size(375, 812), minTextAdapt: true, builder: (context, child) { - return{{/screen_util}} blocBuilder( - builder: (context, state) { + return{{/screen_util}} + ThemeModeSwitcher( + builder: (context, themeMode, _) { return MaterialApp.router( debugShowCheckedModeBanner: false, builder: (context, widget) { @@ -55,12 +55,17 @@ class _AppState extends BaseState { scrollBehavior: const CupertinoScrollBehavior(), theme: createLightTheme(), darkTheme: createDarkTheme(), - themeMode: state.themeMode, - {{#isGoRouter}}routeInformationProvider: AppRouter.router.routeInformationProvider,{{/isGoRouter}} - routeInformationParser: {{#isGoRouter}}AppRouter.router.routeInformationParser,{{/isGoRouter}} - {{^isGoRouter}}appRouter().defaultRouteParser(),{{/isGoRouter}} - routerDelegate: {{#isGoRouter}}AppRouter.router.routerDelegate,{{/isGoRouter}} - {{^isGoRouter}}appRouter().delegate(),{{/isGoRouter}} + themeMode: themeMode, + {{^isGoRouter}} + {{^sentry}}routerConfig: appRouter().config(),{{/sentry}} + {{#sentry}}routerConfig: appRouter().config( + navigatorObservers: () => [ + SentryNavigatorObserver(), + ], + ), + {{/sentry}} + {{/isGoRouter}} + {{#isGoRouter}}routerConfig: AppRouter.router,{{/isGoRouter}} locale: locale, {{^handLocalization}} localizationsDelegates: const [ diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/bloc/app_bloc.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/bloc/app_bloc.dart deleted file mode 100644 index fcad8f0d..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/bloc/app_bloc.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'package:{{project_name}}/app/bloc/app_bloc_imports.dart'; -import 'package:{{project_name}}/core/arch/bloc/base_bloc.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; - -class AppBloc extends BaseBloc { - AppBloc() : super(const AppScreenState(themeMode: ThemeMode.system)) { - on(_onChangeTheme); - } - - void _onChangeTheme( - ChangeThemeEvent event, - Emitter emit, - ) { - emit(state.copyWith(themeMode: event.mode)); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/bloc/app_bloc_imports.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/bloc/app_bloc_imports.dart deleted file mode 100644 index dce02ecb..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/bloc/app_bloc_imports.dart +++ /dev/null @@ -1,2 +0,0 @@ -export 'app_bloc.dart'; -export 'app_models.dart'; diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/bloc/app_models.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/bloc/app_models.dart deleted file mode 100644 index 300704fd..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/bloc/app_models.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:freezed_annotation/freezed_annotation.dart'; - -part 'app_models.freezed.dart'; - -@freezed -class AppEvent with _$AppEvent { - const factory AppEvent.changeTheme(ThemeMode mode) = ChangeThemeEvent; -} - -@freezed -class AppScreenState with _$AppScreenState { - const factory AppScreenState({required ThemeMode themeMode}) = - _AppScreenState; -} - -class AppSR {} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/router/app_router.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/router/app_router.dart index 5588f91c..a1ca2bf0 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/router/app_router.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/router/app_router.dart @@ -3,6 +3,7 @@ {{#isGoRouter}}import 'package:{{project_name}}/app/router/app_route.dart';{{/isGoRouter}} {{#isGoRouter}}import 'package:go_router/go_router.dart';{{/isGoRouter}} {{#isGoRouter}}import 'package:{{project_name}}/core/di/services.dart';{{/isGoRouter}} +{{#isGoRouter}}{{#sentry}}import 'package:sentry_flutter/sentry_flutter.dart';{{/sentry}}{{/isGoRouter}} //{imports end} {{^isGoRouter}} @@ -33,6 +34,11 @@ class AppRouter {{^isGoRouter}}extends RootStackRouter{{/isGoRouter}}{ routes: [ //{routes end} ], + {{#sentry}} + observers: [ + SentryNavigatorObserver(), + ], + {{/sentry}} ); }{{/isGoRouter}} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/service/app_service.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/service/app_service.dart index 561e6224..d5a9bfaa 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/service/app_service.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/service/app_service.dart @@ -2,7 +2,7 @@ import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter_jailbreak_detection/flutter_jailbreak_detection.dart'; +import 'package:jailbreak_root_detection/jailbreak_root_detection.dart'; /* * Example of .env file * @@ -12,15 +12,15 @@ import 'package:flutter_jailbreak_detection/flutter_jailbreak_detection.dart'; */ class AppService { - static const apiKey1 = 'APIKEY1'; - static const apiKey2 = 'APIKEY2'; + static const String apiKey1 = 'APIKEY1'; + static const String apiKey2 = 'APIKEY2'; //Change if not need to check for root or jail brake final _secureFromJailbreak = true; Future initialize() async { if (_secureFromJailbreak && !kIsWeb && !kDebugMode) { - final isJailBroken = await FlutterJailbreakDetection.jailbroken; + final isJailBroken = await JailbreakRootDetection.instance.isJailBroken; if (isJailBroken) { return false; } diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/dimensions.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/dimensions.dart index 2f8abfcf..6f958a54 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/dimensions.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/dimensions.dart @@ -1,6 +1,6 @@ {{#screen_util}}import 'package:flutter_screenutil/flutter_screenutil.dart';{{/screen_util}} -final class Dimensions { +class Dimensions { {{#screen_util}} static final delimiterH10 = 10.h;{{/screen_util}} {{^screen_util}} static const delimiterH10 = 10.0;{{/screen_util}} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/extension/failure_message_extension.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/extension/failure_message_extension.dart index c9bf82e0..a573c562 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/extension/failure_message_extension.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/extension/failure_message_extension.dart @@ -1,8 +1,8 @@ //@formatter:off {{#handLocalization}}import 'package:{{project_name}}/app/localization/common_app_localization_ext.dart';{{/handLocalization}} {{^handLocalization}}import 'package:{{project_name}}/app/localization/generated/l10n.dart';{{/handLocalization}} -import 'package:{{project_name}}/core/arch/domain/entity/failure/api_failure.dart'; -{{#firebase_auth}}import 'package:{{project_name}}/core/arch/domain/entity/failure/firebase_failure.dart';{{/firebase_auth}} +{{#firebase_auth}}import 'package:{{project_name}}/domain/entity/failure/firebase_failure.dart';{{/firebase_auth}} +import 'package:onix_flutter_core_models/onix_flutter_core_models.dart'; import 'package:flutter/material.dart'; extension FailureMessageExtension on BuildContext { diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/extension/theme_brightness_extension.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/extension/theme_brightness_extension.dart index 9ea00454..7ba7cd5b 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/extension/theme_brightness_extension.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/extension/theme_brightness_extension.dart @@ -1,6 +1,5 @@ -import 'package:{{project_name}}/app/bloc/app_bloc_imports.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:{{project_name}}/core/arch/widget/common/theme_switcher.dart'; extension ThemeBrightnessExtension on BuildContext { bool get isDarkMode => Theme.of(this).brightness == Brightness.dark; @@ -30,10 +29,7 @@ extension ThemeBrightnessExtension on BuildContext { break; } } - BlocProvider.of(this).add( - AppEvent.changeTheme( - newThemeMode, - ), - ); + + ThemeModeNotifier.of(this).changeTheme(newThemeMode); } } diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/qa_utils.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/qa_utils.dart index 53720b9f..5fdef649 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/qa_utils.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/app/util/qa_utils.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; import 'package:{{project_name}}/core/arch/widget/common/toast.dart'; -final class QaUtils { +class QaUtils { static Widget buildCharlesProxyBtn(_) { return const SizedBox(); //TODO SHOW set proxy ONLY FOR QA BUILDS diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/app_bloc_observer.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/app_bloc_observer.dart deleted file mode 100644 index 5ed972c7..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/app_bloc_observer.dart +++ /dev/null @@ -1,16 +0,0 @@ -import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; - -class AppBlocObserver extends BlocObserver { - @override - void onEvent(Bloc bloc, Object? event) { - logger.d('$event'); - super.onEvent(bloc, event); - } - - @override - void onError(BlocBase bloc, Object error, StackTrace stackTrace) { - logger.d('$stackTrace'); - super.onError(bloc, error, stackTrace); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_bloc.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_bloc.dart deleted file mode 100644 index 1b18532e..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_bloc.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:{{project_name}}/core/arch/bloc/failure_stream_mixin.dart'; -import 'package:{{project_name}}/core/arch/bloc/progress_stream_mixin.dart'; -import 'package:{{project_name}}/core/arch/bloc/sr_mixin.dart'; - -abstract class BaseBloc extends Bloc - with - SingleResultMixin, - ProgressStreamMixin, - FailureStreamMixin { - BaseBloc(super.initialState); - - void dispose() { - closeProgressStream(); - closeFailureStream(); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_bloc_state.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_bloc_state.dart deleted file mode 100644 index db92f6c4..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_bloc_state.dart +++ /dev/null @@ -1,87 +0,0 @@ -//@formatter:off -import 'package:{{project_name}}/core/arch/bloc/base_bloc.dart'; -import 'package:{{project_name}}/core/arch/bloc/bloc_builders_mixin.dart'; -import 'package:{{project_name}}/core/arch/bloc/bloc_typedefs.dart'; -import 'package:{{project_name}}/core/arch/bloc/stream_listener.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/progress_state/progress_state.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:get_it/get_it.dart'; -{{^web_only}}import 'package:loader_overlay/loader_overlay.dart';{{/web_only}} -{{#web_only}}import 'package:flutter_overlay_loader/flutter_overlay_loader.dart'; -import 'package:{{project_name}}/app/util/extension/loader.dart';{{/web_only}} - -abstract class BaseState, SR, -W extends StatefulWidget> extends State - with BlocBuildersMixin { - bool lazyBloc = false; - B? _bloc; - - @override - Widget build(BuildContext context) { - return BlocProvider( - create: (context) { - final bloc = createBloc(); - onBlocCreated(context, bloc); - _bloc = bloc; - return bloc; - }, - lazy: lazyBloc, - child: Builder( - builder: (context) { - initParams(context); - return buildWidget(context); - }, - ), - ); - } - - @override - void dispose() { - {{#web_only}}Loader.hide();{{/web_only}} - {{^web_only}}if (context.mounted) { - context.loaderOverlay.hide(); - }{{/web_only}} - if (_bloc != null) { - _bloc?.dispose(); - } - super.dispose(); - } - - B blocOf(BuildContext context) => context.read(); - - B createBloc() => GetIt.I.get(); - - Widget srObserver({ - required BuildContext context, - required Widget child, - required SingleResultListener onSR, - }) { - return StreamListener( - stream: (_bloc ?? blocOf(context)).singleResults, - onData: (data) { - onSR(context, data); - }, - child: child, - ); - } - - void onBlocCreated(BuildContext context, B bloc) { - bloc.progressStream.listen((event) async { - if (event is DefaultProgressState) { - if (event.showProgress) { - {{#web_only}}context.progressShow();{{/web_only}} - {{^web_only}}context.loaderOverlay.show();{{/web_only}} - } else { - {{#web_only}}context.progressHide();{{/web_only}} - {{^web_only}}context.loaderOverlay.hide();{{/web_only}} - } - } - }); - } - - // ignore: no-empty-block - void initParams(BuildContext context) {} - - Widget buildWidget(BuildContext context); -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_cubit.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_cubit.dart deleted file mode 100644 index 4b875023..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_cubit.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:{{project_name}}/core/arch/bloc/failure_stream_mixin.dart'; -import 'package:{{project_name}}/core/arch/bloc/progress_stream_mixin.dart'; -import 'package:{{project_name}}/core/arch/bloc/sr_cubit_mixin.dart'; - -abstract class BaseCubit extends Cubit - with - SingleResultCubitMixin, - ProgressStreamMixin, - FailureStreamMixin { - BaseCubit(super.initialState); - - void dispose() { - closeProgressStream(); - closeFailureStream(); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_cubit_state.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_cubit_state.dart deleted file mode 100644 index 499df4a5..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/base_cubit_state.dart +++ /dev/null @@ -1,87 +0,0 @@ -//@formatter:off -import 'package:{{project_name}}/core/arch/bloc/base_cubit.dart'; -import 'package:{{project_name}}/core/arch/bloc/bloc_builders_mixin.dart'; -import 'package:{{project_name}}/core/arch/bloc/bloc_typedefs.dart'; -import 'package:{{project_name}}/core/arch/bloc/stream_listener.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/progress_state/progress_state.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:get_it/get_it.dart'; -{{^web_only}}import 'package:loader_overlay/loader_overlay.dart';{{/web_only}} -{{#web_only}}import 'package:flutter_overlay_loader/flutter_overlay_loader.dart'; -import 'package:{{project_name}}/app/util/extension/loader.dart';{{/web_only}} - -abstract class BaseCubitState, SR, -W extends StatefulWidget> extends State - with BlocBuildersMixin { - bool lazyCubit = false; - C? _cubit; - - @override - Widget build(BuildContext context) { - return BlocProvider( - create: (context) { - final cubit = createCubit(); - onCubitCreated(context, cubit); - _cubit = cubit; - return cubit; - }, - lazy: lazyCubit, - child: Builder( - builder: (context) { - initParams(context); - return buildWidget(context); - }, - ), - ); - } - - @override - void dispose() { - {{#web_only}}Loader.hide();{{/web_only}} - {{^web_only}}if (context.mounted) { - context.loaderOverlay.hide(); - }{{/web_only}} - if (_cubit != null) { - _cubit?.dispose(); - } - super.dispose(); - } - - C cubitOf(BuildContext context) => context.read(); - - C createCubit() => GetIt.I.get(); - - Widget srObserver({ - required BuildContext context, - required Widget child, - required SingleResultListener onSR, - }) { - return StreamListener( - stream: (_cubit ?? cubitOf(context)).singleResults, - onData: (data) { - onSR(context, data); - }, - child: child, - ); - } - - void onCubitCreated(BuildContext context, C cubit) { - cubit.progressStream.listen((event) async { - if (event is DefaultProgressState) { - if (event.showProgress) { - {{#web_only}}context.progressShow();{{/web_only}} - {{^web_only}}context.loaderOverlay.show();{{/web_only}} - } else { - {{#web_only}}context.progressHide();{{/web_only}} - {{^web_only}}context.loaderOverlay.hide();{{/web_only}} - } - } - }); - } - - // ignore: no-empty-block - void initParams(BuildContext context) {} - - Widget buildWidget(BuildContext context); -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/bloc_builders_mixin.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/bloc_builders_mixin.dart deleted file mode 100644 index bfca8999..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/bloc_builders_mixin.dart +++ /dev/null @@ -1,38 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:{{project_name}}/core/arch/bloc/bloc_typedefs.dart'; - -mixin BlocBuildersMixin, S, SR> { - Widget blocConsumer({ - required StateListener builder, - required ListenDelegate listener, - BlocBuilderCondition? buildWhen, - BlocListenerCondition? listenWhen, - }) { - return BlocConsumer( - builder: (_, state) => builder(state), - listener: listener, - buildWhen: buildWhen, - listenWhen: listenWhen, - ); - } - - Widget blocBuilder({ - required BlocWidgetBuilder builder, - BlocBuilderCondition? buildWhen, - }) { - return BlocBuilder(builder: builder, buildWhen: buildWhen); - } - - Widget blocListener({ - required ListenDelegate listener, - Widget? child, - BlocListenerCondition? listenWhen, - }) { - return BlocListener( - listener: listener, - listenWhen: listenWhen, - child: child, - ); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/bloc_typedefs.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/bloc_typedefs.dart deleted file mode 100644 index b9021aab..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/bloc_typedefs.dart +++ /dev/null @@ -1,8 +0,0 @@ -import 'package:flutter/material.dart'; - -typedef ListenDelegate = void Function(BuildContext context, S state); -typedef StateListener = Widget Function(S state); -typedef SingleResultListener = void Function( - BuildContext context, - SR singleResult, -); diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/failure_stream_mixin.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/failure_stream_mixin.dart deleted file mode 100644 index 27144ef6..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/failure_stream_mixin.dart +++ /dev/null @@ -1,22 +0,0 @@ -import 'dart:async'; - -import 'package:{{project_name}}/core/arch/domain/entity/failure/failure.dart'; - -mixin class FailureStreamMixin { - final StreamController _errorStreamController = - StreamController.broadcast(); - - Stream get failureStream => _errorStreamController.stream; - - void onFailure(Failure failure) { - if (!_errorStreamController.isClosed) { - _errorStreamController.add(failure); - } - } - - void closeFailureStream() { - if (!_errorStreamController.isClosed) { - _errorStreamController.close(); - } - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/progress_stream_mixin.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/progress_stream_mixin.dart deleted file mode 100644 index 3bf2fe3b..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/progress_stream_mixin.dart +++ /dev/null @@ -1,34 +0,0 @@ -import 'dart:async'; - -import 'package:{{project_name}}/core/arch/domain/entity/progress_state/progress_state.dart'; - -mixin class ProgressStreamMixin { - final StreamController _progressStreamController = - StreamController.broadcast(); - - Stream get progressStream => - _progressStreamController.stream; - - void showProgress({BaseProgressState? state}) { - if (!_progressStreamController.isClosed) { - _progressStreamController.add( - state ?? const DefaultProgressState(showProgress: true), - ); - } - } - - Future hideProgress({BaseProgressState? state}) async { - await Future.delayed(const Duration(milliseconds: 50)); - if (!_progressStreamController.isClosed) { - _progressStreamController.add( - state ?? const DefaultProgressState(showProgress: false), - ); - } - } - - void closeProgressStream() { - if (!_progressStreamController.isClosed) { - _progressStreamController.close(); - } - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/sr_cubit_mixin.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/sr_cubit_mixin.dart deleted file mode 100644 index 1d77f806..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/sr_cubit_mixin.dart +++ /dev/null @@ -1,41 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; - -/// Mixin for extending the block's capabilities to support SingleResult - -/// events that need to be rendered 1 time -/// - Navigation -/// - Toast -/// - Snack -/// - Some interaction with the animation -mixin SingleResultCubitMixin on Cubit - implements SingleResultProvider, SingleResultEmitter { - @protected - final StreamController _srController = StreamController.broadcast(); - - @override - Stream get singleResults => _srController.stream; - - @override - void addSr(SR sr) { - if (!_srController.isClosed) _srController.add(sr); - } - - @override - Future close() { - _srController.close(); - return super.close(); - } -} - -/// Protocol for providing a stream of events [SingleResult] -abstract class SingleResultProvider { - Stream get singleResults; -} - -/// Protocol for receiving events [SingleResult] -//ignore: one_member_abstracts -abstract class SingleResultEmitter { - void addSr(SingleResult sr); -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/sr_mixin.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/sr_mixin.dart deleted file mode 100644 index c3db4c5a..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/sr_mixin.dart +++ /dev/null @@ -1,50 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; - -/// Mixin for extending the block's capabilities to support SingleResult - -/// events that need to be rendered 1 time -/// - Navigation -/// - Toast -/// - Snack -/// - Some interaction with the animation -mixin SingleResultMixin on Bloc - implements SingleResultProvider, SingleResultEmitter { - @protected - final StreamController _srController = StreamController.broadcast(); - - @override - Stream get singleResults => _srController.stream; - - @override - void addSr(SR sr) { - final observer = Bloc.observer; - if (observer is SrBlocObserver) observer.onSr(this, sr); - if (!_srController.isClosed) _srController.add(sr); - } - - @override - Future close() { - _srController.close(); - - return super.close(); - } -} - -/// Protocol for providing a stream of events [SingleResult] -abstract class SingleResultProvider { - Stream get singleResults; -} - -/// Protocol for receiving events [SingleResult] -abstract class SingleResultEmitter { - void addSr(SingleResult sr); -} - -/// Extending Observer to support logging SingleResult events -class SrBlocObserver extends BlocObserver { - @protected - @mustCallSuper - void onSr(Bloc bloc, SR sr) {} -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/stream_listener.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/stream_listener.dart deleted file mode 100644 index 390aee25..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/bloc/stream_listener.dart +++ /dev/null @@ -1,65 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/widgets.dart'; - -/// Widget for managing the Stream [stream] life cycle supplied -/// to the widget tree. -class StreamListener extends StatefulWidget { - final Stream stream; - - final Widget child; - final void Function(T event) onData; - final Function? onError; - final Function()? onDone; - final bool? cancelOnError; - - const StreamListener({ - required this.stream, - required this.child, - required this.onData, - this.onError, - this.onDone, - this.cancelOnError, - super.key, - }); - - @override - State> createState() => _StreamListenerState(); -} - -class _StreamListenerState extends State> { - @override - void initState() { - super.initState(); - listen(); - } - - @override - void didUpdateWidget(covariant StreamListener oldWidget) { - super.didUpdateWidget(oldWidget); - _streamSubs?.cancel(); - listen(); - } - - @override - Widget build(BuildContext context) { - return widget.child; - } - - StreamSubscription? _streamSubs; - - @override - void dispose() { - _streamSubs?.cancel(); - super.dispose(); - } - - void listen() { - _streamSubs = widget.stream.listen( - widget.onData, - onDone: widget.onDone, - onError: widget.onError, - cancelOnError: widget.cancelOnError, - ); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/local/prefs/base_preferences.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/local/prefs/base_preferences.dart deleted file mode 100644 index f9e980b2..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/local/prefs/base_preferences.dart +++ /dev/null @@ -1,55 +0,0 @@ -import 'package:shared_preferences/shared_preferences.dart'; - -class BasePreferences { - Future get(String key, T defaultValue) async { - final prefs = await SharedPreferences.getInstance(); - T result; - - switch (defaultValue.runtimeType) { - case const (String): - final value = prefs.getString(key) as T?; - result = value ?? defaultValue; - case const (bool): - final value = prefs.getBool(key) as T?; - result = value ?? defaultValue; - case const (double): - final value = prefs.getDouble(key) as T?; - result = value ?? defaultValue; - case const (int): - final value = prefs.getInt(key) as T?; - result = value ?? defaultValue; - default: - return defaultValue; - } - return result; - } - - Future put(String key, T value) async { - final prefs = await SharedPreferences.getInstance(); - switch (value.runtimeType) { - case const (String): - await prefs.setString(key, value as String); - case const (bool): - await prefs.setBool(key, value as bool); - case const (double): - await prefs.setDouble(key, value as double); - case const (int): - await prefs.setInt(key, value as int); - } - } - - Future clearPrefs() async { - final prefs = await SharedPreferences.getInstance(); - await prefs.clear(); - } - - Future removePrefByKey(String key) async { - final prefs = await SharedPreferences.getInstance(); - return prefs.remove(key); - } - - Future reload() async { - final prefs = await SharedPreferences.getInstance(); - await prefs.reload(); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/base/base_api_client.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/base/base_api_client.dart deleted file mode 100644 index c28c822e..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/base/base_api_client.dart +++ /dev/null @@ -1,18 +0,0 @@ -abstract class BaseApiClient { - static const String kAuthHeader = 'Authorization'; - static const String kAuthPrefix = 'Bearer '; - static const String kAcceptHeader = 'Accept'; - static const String kContentTypeHeader = 'Content-Type'; - static const String kJsonPrefix = 'application/json'; - static const String kMultipartPrefix = 'multipart/form-data'; - static const String kMediaJPEG = 'image/jpeg'; - static const String kMediaPNG = 'image/png'; - - late T client; - - void attachInterceptors(); - - void deAttachInterceptors(); - - void attachLoggerInterceptor(); -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/base/http_status.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/base/http_status.dart deleted file mode 100644 index 058212ef..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/base/http_status.dart +++ /dev/null @@ -1,17 +0,0 @@ -class HttpStatus { - static const int kCodeSuccess200 = 200; - static const int kCodeSuccess201 = 201; - static const int badRequest = 400; - static const int unauthorized = 401; - static const int forbidden = 403; - static const int notFound = 404; - static const int unprocessedEntity = 422; - static const int unsupportedMediaType = 415; - static const int internalServerError = 500; - static const int notImplemented = 501; - static const int badGateway = 502; - static const int serviceUnavailable = 503; - - static const int networkConnectTimeoutError = 599; - static const int tooManyRequests = 429; -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/base/map_common_server_error.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/base/map_common_server_error.dart deleted file mode 100644 index c8296fb4..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/base/map_common_server_error.dart +++ /dev/null @@ -1,45 +0,0 @@ -//@formatter:off -import 'package:{{project_name}}/core/arch/data/remote/error/default_api_error.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/failure/api_failure.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/failure/canceled_request_failure.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/failure/failure.dart'; -import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; - -class MapCommonServerError { - static Failure getServerFailureDetails( - DataResponse failure, - ) { - try { - return failure.maybeWhen( - undefinedError: (error, statusCode) => ApiFailure( - ServerFailure.unknown, - statusCode: statusCode, - message: error.toString(), - ), - apiError: _getResponseError, - notConnected: () => ApiFailure(ServerFailure.noNetwork), - unauthorized: () => ApiFailure(ServerFailure.unAuthorized), - tooManyRequests: () => ApiFailure(ServerFailure.tooManyRequests), - canceledRequest: () => const CanceledRequestFailure(), - orElse: () => ApiFailure(ServerFailure.unknown), - ); - } catch (e, trace) { - logger.crash(reason: 'Mapping Error Failed', error: e, stackTrace: trace); - return ApiFailure(ServerFailure.exception, message: e.toString()); - } - } - - static ApiFailure _getResponseError(customError, int? statusCode) { - if (customError is DefaultApiError) { - return ApiFailure( - ServerFailure.response, - message: customError.name, - statusCode: statusCode, - ); - } - //TODO process other error types and provide results - //TODO also add new error types to DataResponse if needed - return ApiFailure(ServerFailure.response); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/api_client.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/api_client.dart deleted file mode 100644 index 346edcde..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/api_client.dart +++ /dev/null @@ -1,91 +0,0 @@ -import 'dart:io'; - -import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; -import 'package:dio/dio.dart'; -import 'package:dio/io.dart'; -import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; -import 'package:flutter/foundation.dart'; -import 'package:pretty_dio_logger/pretty_dio_logger.dart'; - -import 'package:{{project_name}}/core/arch/data/remote/base/base_api_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/interceptor/basic_app_auth_interceptor.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/interceptor/cache_interceptor.dart'; - -class ApiClient implements BaseApiClient { - static const defaultConnectTimeout = 30000; - static const defaultReceiveTimeout = 30000; - - ApiClient({required BaseOptions options}) { - client = Dio(options); - customInterceptor = BasicAppAuthInterceptor(); - cacheInterceptor = CacheInterceptor(client); - client.transformer = BackgroundTransformer(); - attachLoggerInterceptor(); - } - - late BasicAppAuthInterceptor customInterceptor; - late CacheInterceptor cacheInterceptor; - - CacheOptions? get cacheOptions => cacheInterceptor.cacheOptions; - - @override - late Dio client; - - @override - void attachLoggerInterceptor() { - if (kDebugMode) { - client.interceptors.add( - PrettyDioLogger( - requestHeader: true, - requestBody: true, - responseHeader: true, - compact: false, - ), - ); - } - } - - @override - void attachInterceptors() { - client.interceptors.remove(customInterceptor); - client.interceptors.add(customInterceptor); - _attachCacheInterceptor(); - } - - @override - void deAttachInterceptors() { - client.interceptors.remove(customInterceptor); - clearCache(); - } - - void attachCharlesProxy(String? charlesIp, String? port) { - if (charlesIp == null || port == null) return; - - client.httpClientAdapter = IOHttpClientAdapter( - createHttpClient: () { - final client = HttpClient() - ..findProxy = (uri) => 'PROXY $charlesIp:$port'; - - //ignore: cascade_invocations - client.badCertificateCallback = (cert, host, port) => true; - return client; - }, - ); - - logger.d('CharlesProxyEnabled'); - } - - CachePolicy getCachePolicy({required bool forceRefresh}) => - cacheInterceptor.getCachePolicy(forceRefresh: forceRefresh); - - Future clearCache() async { - logger.d('clearCache'); - await cacheInterceptor.clearCache(); - await _attachCacheInterceptor(); - } - - Future _attachCacheInterceptor() async { - logger.d('attachCacheInterceptor'); - await cacheInterceptor.attachCacheInterceptor(); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_client_module.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_client_module.dart deleted file mode 100644 index 53c52c20..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_client_module.dart +++ /dev/null @@ -1,31 +0,0 @@ -import 'package:connectivity_plus/connectivity_plus.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor_impl.dart'; -import 'package:{{project_name}}/core/arch/data/remote/base/base_api_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/api_client.dart'; -import 'package:dio/dio.dart'; -import 'package:internet_connection_checker/internet_connection_checker.dart'; -import 'package:flutter/foundation.dart' show kIsWeb; - -abstract class DioClientModule { - ApiClient makeApiClient(String baseUrl) => ApiClient( - options: BaseOptions( - baseUrl: baseUrl, - connectTimeout: - const Duration(milliseconds: ApiClient.defaultConnectTimeout), - receiveTimeout: - const Duration(milliseconds: ApiClient.defaultReceiveTimeout), - headers: { - BaseApiClient.kAcceptHeader: BaseApiClient.kJsonPrefix, - BaseApiClient.kContentTypeHeader: BaseApiClient.kJsonPrefix, - }, - ), - ); - - DioRequestProcessor makeDioErrorHandler() => kIsWeb - ? DioRequestProcessorImpl() - : DioRequestProcessorImpl( - connectivity: Connectivity(), - internetConnectionChecker: InternetConnectionChecker(), - ); -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor.dart deleted file mode 100644 index 60e4eab6..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor.dart +++ /dev/null @@ -1,24 +0,0 @@ -import 'dart:async'; -import 'package:{{project_name}}/core/arch/data/remote/error/dio_error_processor.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; -import 'package:dio/dio.dart'; - -///Custom function to provide request Future -typedef OnRequest = Future Function(); - -///Custom Function to provide response converter (Map to Object) -typedef OnResponse = T Function(Response response); - -abstract class DioRequestProcessor { - ///Pass 2 required functions: - ///onRequest - your request Future - ///onResponse - your response converter, basically call fromJson inside - ///checkNetworkConnection - set to false if you need get data from - ///cache interceptor - Future> processRequest({ - required OnRequest onRequest, - required OnResponse onResponse, - bool checkNetworkConnection = true, - OnCustomError? onCustomError, - }); -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor_impl.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor_impl.dart deleted file mode 100644 index f3c8a666..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor_impl.dart +++ /dev/null @@ -1,112 +0,0 @@ -import 'dart:async'; -import 'dart:io'; - -import 'package:{{project_name}}/core/arch/data/remote/base/http_status.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; -import 'package:{{project_name}}/core/arch/data/remote/error/dio_error_processor.dart'; -import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; -import 'package:connectivity_plus/connectivity_plus.dart'; -import 'package:dio/dio.dart'; -import 'package:flutter/material.dart'; -import 'package:internet_connection_checker/internet_connection_checker.dart'; -import 'package:retry/retry.dart'; - -class DioRequestProcessorImpl implements DioRequestProcessor { - /// Number of attempts to re-execute the request - static const defaultMaxAttemptsCount = 2; - - /// Error codes that require re-execution of the request (without bad request) - /// Basic list of error codes that require re-execution of the request - static const defaultRetryStatusCodes = [ - HttpStatus.badGateway, - HttpStatus.serviceUnavailable, - ]; - - @protected - final Connectivity? connectivity; - @protected - final InternetConnectionChecker? internetConnectionChecker; - final int maxAttemptsCount; - @protected - final bool useRetry; - @protected - final List retryStatusCodes; - final _errorProcessor = const DioErrorProcessor(); - - DioRequestProcessorImpl({ - this.connectivity, - this.internetConnectionChecker, - this.useRetry = false, - this.maxAttemptsCount = defaultMaxAttemptsCount, - this.retryStatusCodes = defaultRetryStatusCodes, - }); - - @override - Future> processRequest({ - required OnRequest onRequest, - required OnResponse onResponse, - bool checkNetworkConnection = true, - OnCustomError? onCustomError, - }) async { - if (connectivity != null && internetConnectionChecker != null) { - final resultConnectivity = - await connectivity?.checkConnectivity() ?? false; - final hasConnection = - await internetConnectionChecker?.hasConnection ?? false; - - if (checkNetworkConnection && - (resultConnectivity == ConnectivityResult.none || !hasConnection)) { - return DataResponse.notConnected(); - } - } - - try { - final response = await _call(onRequest); - return DataResponse.success(onResponse(response as Response)); - } on DioException catch (e, trace) { - if(e.type == DioExceptionType.cancel) { - return const DataResponse.canceledRequest(); - } - logger.crash(reason: 'onDioError', error: e, stackTrace: trace); - return _errorProcessor.processError( - e, - onCustomError: onCustomError, - ); - } catch (e, trace) { - logger.crash(reason: 'onDioCommonError', error: e, stackTrace: trace); - return DataResponse.undefinedError(e); - } - } - - Future _call(OnRequest request) async { - if (useRetry) { - return retry( - request, - maxAttempts: maxAttemptsCount, - retryIf: (exception) => _retryPolicy( - exception: exception, - retryStatusCodes: retryStatusCodes, - ), - ); - } else { - return request(); - } - } - - FutureOr _retryPolicy({ - required Exception exception, - required List retryStatusCodes, - }) { - if (exception is! DioException) return false; - if (exception.type == DioExceptionType.cancel) return false; - final response = exception.response; - if (response == null) { - return true; - } - if (exception is SocketException || exception is TimeoutException) { - return true; - } - return retryStatusCodes.contains(response.statusCode); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/interceptor/authorization_interceptor.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/interceptor/authorization_interceptor.dart deleted file mode 100644 index dea93d75..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/interceptor/authorization_interceptor.dart +++ /dev/null @@ -1,130 +0,0 @@ -import 'package:{{project_name}}/core/arch/data/remote/base/base_api_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/base/http_status.dart'; -import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; -import 'package:{{project_name}}/core/di/repository.dart'; -import 'package:{{project_name}}/core/di/services.dart'; -import 'package:{{project_name}}/data/mapper/authentication/authentication_mapper.dart'; -import 'package:{{project_name}}/data/model/remote/authentication/authentication_response.dart'; -import 'package:{{project_name}}/data/model/remote/token/token_request.dart'; -import 'package:{{project_name}}/domain/entity/authentication/authentication.dart'; -import 'package:dio/dio.dart'; - -class AuthorizationInterceptor extends QueuedInterceptorsWrapper { - late Dio _refreshDio; - - //TODO change refresh path - final _refreshPath = 'auth/refresh'; - - AuthorizationInterceptor() { - _refreshDio = Dio(); - } - - @override - Future onRequest( - RequestOptions options, - RequestInterceptorHandler handler, - ) async { - final token = tokenRepository.accessToken; - if (token != null && token.isNotEmpty) { - options.headers.addAll( - { - BaseApiClient.kAuthHeader: '${BaseApiClient.kAuthPrefix}$token', - }, - ); - } - logger.d('token: $token'); - handler.next(options); - } - - @override - Future onError( - DioException err, - ErrorInterceptorHandler handler, - ) async { - if (err.response?.statusCode == HttpStatus.unauthorized) { - final refreshToken = tokenRepository.refreshToken; - final accessToken = tokenRepository.accessToken; - try { - if (refreshToken == null || - refreshToken.isEmpty || - accessToken == null || - accessToken.isEmpty) { - await sessionService().closeSession(); - return handler.next(err); - } - final request = TokenRequest( - accessToken: accessToken, - refreshToken: refreshToken, - ); - final authEntity = await _refresh(err, request); - return await _resolveRequest(err, handler, authEntity); - } on DioException { - if (err.response?.statusCode == HttpStatus.unauthorized) { - await sessionService().closeSession(); - } - } catch (e, stackTrace) { - logger.crash(error: e, stackTrace: stackTrace); - await sessionService().closeSession(); - } - } - handler.next(err); - } - - Future _refresh( - DioException err, - TokenRequest request, - ) async { - logger.d('_refresh start'); - final result = await _refreshDio.post( - '${err.requestOptions.baseUrl}$_refreshPath', - options: Options( - headers: { - BaseApiClient.kAcceptHeader: BaseApiClient.kJsonPrefix, - BaseApiClient.kContentTypeHeader: BaseApiClient.kJsonPrefix, - BaseApiClient.kAuthHeader: - '${BaseApiClient.kAuthPrefix}${request.accessToken}', - }, - ), - data: request.toJson(), - ); - final data = AuthenticationResponse.fromJson( - result.data['data'], - ); - logger.d('_refresh end'); - return AuthenticationMappers().mapRefreshEntity(data); - } - - Future _resolveRequest( - DioException err, - ErrorInterceptorHandler handler, - Authentication authEntity, - ) async { - await tokenRepository.update( - Authentication( - accessToken: authEntity.accessToken, - refreshToken: authEntity.refreshToken, - ), - ); - final requestOptions = err.response?.requestOptions; - if (requestOptions != null) { - requestOptions.headers[BaseApiClient.kAuthHeader] = - '${BaseApiClient.kAuthPrefix}${authEntity.accessToken}'; - final options = Options( - method: requestOptions.method, - headers: requestOptions.headers, - ); - final dioRefresh = Dio( - BaseOptions(baseUrl: requestOptions.baseUrl), - ); - final response = await dioRefresh.request( - requestOptions.path, - data: requestOptions.data, - queryParameters: requestOptions.queryParameters, - options: options, - ); - return handler.resolve(response); - } - logger.e('err: $err'); - return handler.next(err); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/interceptor/basic_app_auth_interceptor.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/interceptor/basic_app_auth_interceptor.dart deleted file mode 100644 index d5394fe5..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/interceptor/basic_app_auth_interceptor.dart +++ /dev/null @@ -1,27 +0,0 @@ -import 'dart:io'; - -import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; -import 'package:dio/dio.dart'; - -class BasicAppAuthInterceptor extends InterceptorsWrapper { - @override - void onRequest(RequestOptions options, RequestInterceptorHandler handler) { - logger.d('AppInterceptor onRequest'); - //TODO add accessToken - // var accessToken = 'some token'; - // options.headers[kAuthHeader] = '$kAuthPrefix$accessToken'; - // options.headers[kAcceptHeader] = kJsonPrefix; - // options.headers[kContentTypeHeader] = kJsonPrefix; - super.onRequest(options, handler); - } - - @override - void onError(DioException err, ErrorInterceptorHandler handler) { - logger.d('AppInterceptor start: $err'); - if (err.response?.statusCode == HttpStatus.unauthorized) { - //TODO disposeSessionLocal - return; - } - super.onError(err, handler); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/interceptor/cache_interceptor.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/interceptor/cache_interceptor.dart deleted file mode 100644 index ef463177..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/interceptor/cache_interceptor.dart +++ /dev/null @@ -1,81 +0,0 @@ -import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; -import 'package:{{project_name}}/core/di/local.dart'; -import 'package:{{project_name}}/data/source/local/secure_storage/secure_storage_keys.dart'; -import 'package:dio/io.dart'; -import 'dart:io'; -import 'package:dio/dio.dart'; -import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; -import 'package:dio_cache_interceptor_hive_store/dio_cache_interceptor_hive_store.dart'; -import 'package:{{project_name}}/app/service/hive_cipher_key_service.dart'; -import 'package:path_provider/path_provider.dart' as pp; -import 'package:hive_flutter/hive_flutter.dart'; - -class CacheInterceptor { - final Dio client; - - CacheOptions? cacheOptions; - HiveCacheStore? _cacheStore; - DioCacheInterceptor? _interceptor; - - CacheInterceptor(this.client); - - Future attachCacheInterceptor() async { - try { - final options = await createOptions(); - final interceptor = DioCacheInterceptor(options: options); - _interceptor = interceptor; - - client.interceptors.add(interceptor); - cacheOptions = options; - - client.httpClientAdapter = IOHttpClientAdapter( - createHttpClient: () { - final client = HttpClient(); - //ignore: cascade_invocations - client.badCertificateCallback = (cert, host, port) => true; - return client; - }, - ); - - logger.d('DioCacheInterceptor ADDED'); - } catch (e, trace) { - logger.crash( - reason: 'DioCacheInterceptor Error', - error: e, - stackTrace: trace, - ); - } - } - - Future createOptions() async { - final dir = await pp.getApplicationDocumentsDirectory(); - final keyService = HiveCipherKeyService(secureStorageSource()); - final key = await keyService.init(); - - _cacheStore = - HiveCacheStore(dir.path, encryptionCipher: HiveAesCipher(key)); - - return CacheOptions( - store: _cacheStore, - policy: CachePolicy.noCache, - hitCacheOnErrorExcept: [], - maxStale: const Duration(days: 1), - allowPostMethod: true, - ); - } - - CachePolicy getCachePolicy({required bool forceRefresh}) { - return forceRefresh - ? CachePolicy.refreshForceCache - : CachePolicy.forceCache; - } - - Future clearCache() async { - await secureStorageSource().delete(SecureStorageKeys.kSecretKeyCipher); - await _cacheStore?.clean(); - } - - void deAttachInterceptor() { - client.interceptors.remove(_interceptor); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/graph_ql_const.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/graph_ql_const.dart deleted file mode 100644 index 381eee54..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/graph_ql_const.dart +++ /dev/null @@ -1,3 +0,0 @@ -class GraphQlConst { - static const String graphQLBaseUrl = 'https://jsonplaceholder.typicode.com'; -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_const.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/dio/dio_const.dart similarity index 90% rename from bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_const.dart rename to bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/dio/dio_const.dart index 6b7475d1..b5bda011 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/dio/dio_const.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/dio/dio_const.dart @@ -4,5 +4,6 @@ class DioConst { static const String defaultApiClientName = 'DefaultApiClient'; + const DioConst._(); //{dio const end} } diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/default_api_error.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/default_api_error.dart index 331b983b..794df1e0 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/default_api_error.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/default_api_error.dart @@ -1,7 +1,6 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'default_api_error.freezed.dart'; - part 'default_api_error.g.dart'; //TODO Modify this class to make it like Your Api error diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/default_api_error.freezed.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/default_api_error.freezed.dart new file mode 100644 index 00000000..6792e96a --- /dev/null +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/default_api_error.freezed.dart @@ -0,0 +1,183 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'default_api_error.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +DefaultApiError _$DefaultApiErrorFromJson(Map json) { + return _DefaultApiError.fromJson(json); +} + +/// @nodoc +mixin _$DefaultApiError { + String get name => throw _privateConstructorUsedError; + String get code => throw _privateConstructorUsedError; + + /// Serializes this DefaultApiError to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of DefaultApiError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $DefaultApiErrorCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DefaultApiErrorCopyWith<$Res> { + factory $DefaultApiErrorCopyWith( + DefaultApiError value, $Res Function(DefaultApiError) then) = + _$DefaultApiErrorCopyWithImpl<$Res, DefaultApiError>; + @useResult + $Res call({String name, String code}); +} + +/// @nodoc +class _$DefaultApiErrorCopyWithImpl<$Res, $Val extends DefaultApiError> + implements $DefaultApiErrorCopyWith<$Res> { + _$DefaultApiErrorCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of DefaultApiError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? code = null, + }) { + return _then(_value.copyWith( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + code: null == code + ? _value.code + : code // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$DefaultApiErrorImplCopyWith<$Res> + implements $DefaultApiErrorCopyWith<$Res> { + factory _$$DefaultApiErrorImplCopyWith(_$DefaultApiErrorImpl value, + $Res Function(_$DefaultApiErrorImpl) then) = + __$$DefaultApiErrorImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String name, String code}); +} + +/// @nodoc +class __$$DefaultApiErrorImplCopyWithImpl<$Res> + extends _$DefaultApiErrorCopyWithImpl<$Res, _$DefaultApiErrorImpl> + implements _$$DefaultApiErrorImplCopyWith<$Res> { + __$$DefaultApiErrorImplCopyWithImpl( + _$DefaultApiErrorImpl _value, $Res Function(_$DefaultApiErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of DefaultApiError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? code = null, + }) { + return _then(_$DefaultApiErrorImpl( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + code: null == code + ? _value.code + : code // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$DefaultApiErrorImpl implements _DefaultApiError { + const _$DefaultApiErrorImpl({required this.name, required this.code}); + + factory _$DefaultApiErrorImpl.fromJson(Map json) => + _$$DefaultApiErrorImplFromJson(json); + + @override + final String name; + @override + final String code; + + @override + String toString() { + return 'DefaultApiError(name: $name, code: $code)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DefaultApiErrorImpl && + (identical(other.name, name) || other.name == name) && + (identical(other.code, code) || other.code == code)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => Object.hash(runtimeType, name, code); + + /// Create a copy of DefaultApiError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$DefaultApiErrorImplCopyWith<_$DefaultApiErrorImpl> get copyWith => + __$$DefaultApiErrorImplCopyWithImpl<_$DefaultApiErrorImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$DefaultApiErrorImplToJson( + this, + ); + } +} + +abstract class _DefaultApiError implements DefaultApiError { + const factory _DefaultApiError( + {required final String name, + required final String code}) = _$DefaultApiErrorImpl; + + factory _DefaultApiError.fromJson(Map json) = + _$DefaultApiErrorImpl.fromJson; + + @override + String get name; + @override + String get code; + + /// Create a copy of DefaultApiError + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$DefaultApiErrorImplCopyWith<_$DefaultApiErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/default_api_error.g.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/default_api_error.g.dart new file mode 100644 index 00000000..509c781e --- /dev/null +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/default_api_error.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'default_api_error.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$DefaultApiErrorImpl _$$DefaultApiErrorImplFromJson( + Map json) => + _$DefaultApiErrorImpl( + name: json['name'] as String, + code: json['code'] as String, + ); + +Map _$$DefaultApiErrorImplToJson( + _$DefaultApiErrorImpl instance) => + { + 'name': instance.name, + 'code': instance.code, + }; diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/dio_error_processor.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/dio_error_processor.dart deleted file mode 100644 index 618e7156..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/error/dio_error_processor.dart +++ /dev/null @@ -1,62 +0,0 @@ -import 'package:{{project_name}}/core/arch/data/remote/base/http_status.dart'; -import 'package:{{project_name}}/core/arch/data/remote/error/default_api_error.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; -import 'package:dio/dio.dart'; - -typedef OnCustomError = dynamic Function( - int code, - Map response, - ); - -class DioErrorProcessor { - const DioErrorProcessor(); - - DataResponse processError( - DioException e, { - OnCustomError? onCustomError, - }) { - final responseData = e.response?.data; - final statusCode = e.response?.statusCode ?? -1; - if (e.type == DioExceptionType.connectionTimeout || - e.type == DioExceptionType.sendTimeout || - statusCode == HttpStatus.networkConnectTimeoutError) { - return DataResponse.notConnected(); - } - if (statusCode == HttpStatus.unauthorized) { - return DataResponse.unauthorized(); - } - if (statusCode == HttpStatus.tooManyRequests) { - return DataResponse.tooManyRequests(); - } - - final errorHandler = onCustomError; - - if (errorHandler != null) { - final apiError = errorHandler(statusCode, responseData); - if (apiError != null) { - return DataResponse.apiError(apiError, statusCode); - } - } - return _default(e); - } - - DataResponse _default(DioException e) { - try { - final response = e.response?.data; - final statusCode = e.response?.statusCode ?? -1; - if (response != null) { - // TODO: process default error there - // TODO: customize DefaultApiError to your purposes - // TODO: also add new error types to DataResponse if needed - - final error = DefaultApiError.fromJson(response); - return DataResponse.apiError(error, statusCode); - } - return DataResponse.undefinedError(e, statusCode); - } catch (_) { - // This is in case the response is not received - // in the form of ResponseType.json - return DataResponse.undefinedError(e); - } - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/graph_ql_client.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/graph_ql_client.dart similarity index 73% rename from bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/graph_ql_client.dart rename to bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/graph_ql_client.dart index 19e98202..8ccf0b05 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/graph_ql_client.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/graph_ql_client.dart @@ -1,6 +1,6 @@ -import 'package:{{project_name}}/core/arch/data/remote/base/base_api_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/graph_ql_const.dart'; import 'package:graphql/client.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; +import 'package:{{project_name}}/core/arch/data/remote/graph_ql/graph_ql_const.dart'; class GraphQlClient implements BaseApiClient { @override @@ -32,4 +32,7 @@ class GraphQlClient implements BaseApiClient { @override void deAttachInterceptors() {} + + @override + void attachCacheInterceptor(CacheInterceptor cacheInterceptor) {} } diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/graph_ql_const.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/graph_ql_const.dart new file mode 100644 index 00000000..a2df4519 --- /dev/null +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/graph_ql_const.dart @@ -0,0 +1,6 @@ +class GraphQlConst { + //TODO: Specify Api client Base URL + static const String graphQLBaseUrl = 'https://host.todo'; + + const GraphQlConst._(); +} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor.dart similarity index 83% rename from bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor.dart rename to bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor.dart index 394043c3..6fed3035 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor.dart @@ -1,7 +1,7 @@ import 'dart:async'; -import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/graph_ql_client.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; +import 'package:{{project_name}}/core/arch/data/remote/graph_ql/graph_ql_client.dart'; ///Custom function to provide request Future typedef OnRequest = Future Function(); diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor_impl.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor_impl.dart similarity index 87% rename from bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor_impl.dart rename to bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor_impl.dart index 30647012..e7e77780 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor_impl.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor_impl.dart @@ -1,8 +1,9 @@ -import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/graph_ql_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; -import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; import 'package:graphql/client.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart' + hide OnRequest, OnResponse; +import 'package:{{project_name}}/core/arch/data/remote/graph_ql/graph_ql_client.dart'; +import 'package:{{project_name}}/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor.dart'; +import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; class GraphQlRequestProcessorImpl implements GraphQlRequestProcessor { @override @@ -32,7 +33,7 @@ class GraphQlRequestProcessorImpl implements GraphQlRequestProcessor { final customerErrors = onSuccess(response); if (customerErrors?.isNotEmpty ?? false) { final error = customerErrors?.join('\n'); - return DataResponse.apiError(error); + return DataResponse.apiError(error ?? ''); } } @@ -67,7 +68,7 @@ class GraphQlRequestProcessorImpl implements GraphQlRequestProcessor { final customerErrors = onSuccess(response); if (customerErrors?.isNotEmpty ?? false) { final error = customerErrors?.join('\n'); - return DataResponse.apiError(error); + return DataResponse.apiError(error ?? ''); } } return DataResponse.success(response); diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/common/converter/mapper.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/common/converter/mapper.dart deleted file mode 100644 index a8a0cf41..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/common/converter/mapper.dart +++ /dev/null @@ -1,10 +0,0 @@ -abstract class Mapper { - E map(T from); -} - -//ignore: one_member_abstracts -abstract class MapperList extends Mapper { - List mapList(List from) { - return from.map(map).toList(); - } -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/base_empty_response.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/base_empty_response.dart deleted file mode 100644 index c46d7c38..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/base_empty_response.dart +++ /dev/null @@ -1,5 +0,0 @@ -class BaseEmptyResponse { - BaseEmptyResponse(); - factory BaseEmptyResponse.fromJson(Map _) => - BaseEmptyResponse(); -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/data_response.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/data_response.dart deleted file mode 100644 index 9cb18d28..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/data_response.dart +++ /dev/null @@ -1,33 +0,0 @@ -import 'package:freezed_annotation/freezed_annotation.dart'; - -part 'data_response.freezed.dart'; - -@freezed -sealed class DataResponse with _$DataResponse { - T get data => (this as _DataResponseSuccess).data; - - const DataResponse._(); - - const factory DataResponse.success(T data) = _DataResponseSuccess; - - const factory DataResponse.undefinedError(Object? errorObject, [ - int? statusCode, - ]) = _UndefinedError; - - const factory DataResponse.apiError(error, [int? statusCode]) = _ApiError; - - const factory DataResponse.notConnected() = _NoInternetConnection; - - const factory DataResponse.unauthorized() = _Unauthorized; - - const factory DataResponse.tooManyRequests() = _TooManyRequests; - - const factory DataResponse.canceledRequest() = _CanceledRequest; - - {{#firebase_auth}}const factory DataResponse.firebaseError( - String code) = _FirebaseError;{{/firebase_auth}} - - bool isSuccess() => this is _DataResponseSuccess; - - bool isError() => this is! _DataResponseSuccess; -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/operation_status.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/operation_status.dart deleted file mode 100644 index 028b7994..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/operation_status.dart +++ /dev/null @@ -1,4 +0,0 @@ -enum OperationStatus { - success, - failed, -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/result.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/result.dart deleted file mode 100644 index bfff7df2..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/common/result.dart +++ /dev/null @@ -1,25 +0,0 @@ -import 'package:{{project_name}}/core/arch/domain/entity/failure/failure.dart'; -import 'package:freezed_annotation/freezed_annotation.dart'; - -part 'result.freezed.dart'; - -@freezed -class Result with _$Result { - bool get success => this is _ResultSuccess; - - bool get isError => this is ResultError; - - ///WARNING. ALWAYS CHECK success == true before call - T get data => (this as _ResultSuccess).data; - - ///WARNING. ALWAYS CHECK isError == true before call - ResultError get error => this as ResultError; - - const Result._(); - - const factory Result.success(T data) = _ResultSuccess; - - const factory Result.error({ - required Failure failure, - }) = ResultError; -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/api_failure.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/api_failure.dart deleted file mode 100644 index 39c84cef..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/api_failure.dart +++ /dev/null @@ -1,28 +0,0 @@ -import 'package:{{project_name}}/core/arch/domain/entity/failure/failure.dart'; - -class ApiFailure implements FeatureFailure { - final ServerFailure failure; - final int? statusCode; - - final String message; - - ApiFailure( - this.failure, { - this.message = '', - this.statusCode, - }); - - @override - String toString() { - return 'ApiFailure{$failure, message: $message, statusCode: $statusCode}'; - } -} - -enum ServerFailure { - noNetwork, - exception, - unAuthorized, - tooManyRequests, - response, - unknown, -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/canceled_request_failure.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/canceled_request_failure.dart deleted file mode 100644 index 172471ba..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/canceled_request_failure.dart +++ /dev/null @@ -1,5 +0,0 @@ -import 'package:{{project_name}}/core/arch/domain/entity/failure/failure.dart'; - -class CanceledRequestFailure implements FeatureFailure { - const CanceledRequestFailure(); -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/failure.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/failure.dart deleted file mode 100644 index 254d9519..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/failure.dart +++ /dev/null @@ -1,15 +0,0 @@ -abstract class Failure {} - -class CommonFailure implements Failure { - CommonFailure(this.e); - - Exception e; -} - -class DataSourceFailure implements Failure { - DataSourceFailure(this.e); - - Exception e; -} - -abstract class FeatureFailure implements Failure {} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/progress_state/progress_state.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/progress_state/progress_state.dart deleted file mode 100644 index e1d8cb23..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/progress_state/progress_state.dart +++ /dev/null @@ -1,10 +0,0 @@ -///To add custom progress data in BLoC extends from this class -abstract class BaseProgressState { - const BaseProgressState(); -} - -class DefaultProgressState extends BaseProgressState { - final bool showProgress; - - const DefaultProgressState({required this.showProgress}); -} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/widget/common/theme_switcher.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/widget/common/theme_switcher.dart new file mode 100644 index 00000000..ca1cf37d --- /dev/null +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/widget/common/theme_switcher.dart @@ -0,0 +1,56 @@ +import 'package:flutter/material.dart'; + +class ThemeModeSwitcher extends StatefulWidget { + final Widget Function(BuildContext, ThemeMode, Widget?) builder; + final ThemeMode initialThemeMode; + + const ThemeModeSwitcher({ + required this.builder, + this.initialThemeMode = ThemeMode.system, + super.key, + }); + + @override + State createState() => _ThemeModeSwitcherState(); +} + +class _ThemeModeSwitcherState extends State { + late final _themeNotifier = ValueNotifier(widget.initialThemeMode); + + @override + Widget build(BuildContext context) { + return ThemeModeNotifier( + notifier: _themeNotifier, + child: ValueListenableBuilder( + valueListenable: _themeNotifier, + builder: widget.builder, + ), + ); + } +} + +class ThemeModeNotifier extends InheritedWidget { + final ValueNotifier notifier; + + const ThemeModeNotifier({ + required this.notifier, + required super.child, + super.key, + }); + + void changeTheme(ThemeMode themeMode) { + notifier.value = themeMode; + } + + static ThemeModeNotifier of(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType()!; + } + + @override + bool updateShouldNotify(covariant ThemeModeNotifier oldWidget) { + if (notifier.value != oldWidget.notifier.value) { + return true; + } + return false; + } +} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/bloc.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/bloc.dart index 2b08d7ee..8510f397 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/bloc.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/bloc.dart @@ -1,9 +1,7 @@ //@formatter:off import 'package:get_it/get_it.dart'; -import 'package:{{project_name}}/app/bloc/app_bloc_imports.dart'; //{imports end} void registerBloc(GetIt getIt) { - getIt.registerFactory(AppBloc.new); //{bloc end} } diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/injection.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/injection.dart index 7ab4feec..c102b446 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/injection.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/injection.dart @@ -1,7 +1,8 @@ import 'package:get_it/get_it.dart'; import 'package:{{project_name}}/core/di/app.dart'; -import 'package:{{project_name}}/core/di/bloc.dart'; +{{#isBloc}}import 'package:{{project_name}}/core/di/bloc.dart';{{/isBloc}} import 'package:{{project_name}}/core/di/local.dart'; +{{#isProvider}}import 'package:{{project_name}}/core/di/provider.dart';{{/isProvider}} import 'package:{{project_name}}/core/di/remote.dart'; import 'package:{{project_name}}/core/di/repository.dart'; import 'package:{{project_name}}/core/di/services.dart'; @@ -17,5 +18,6 @@ void initializeDi(GetIt getIt) { registerApp(getIt); registerAppServices(getIt); registerUseCases(getIt); - registerBloc(getIt); + {{#isBloc}}registerBloc(getIt);{{/isBloc}} + {{#isProvider}}registerProvider(getIt);{{/isProvider}} } diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/local.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/local.dart index bb004b30..15c4da32 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/local.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/local.dart @@ -1,9 +1,9 @@ import 'package:get_it/get_it.dart'; -import 'package:{{project_name}}/core/arch/data/local/prefs/base_preferences.dart'; import 'package:{{project_name}}/data/source/local/preferences_source/preferences_source.dart'; import 'package:{{project_name}}/data/source/local/preferences_source/preferences_source_impl.dart'; import 'package:{{project_name}}/data/source/local/secure_storage/secure_storage_source.dart'; import 'package:{{project_name}}/data/source/local/secure_storage/secure_storage_source_impl.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; void registerLocal(GetIt getIt) { getIt diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/provider.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/provider.dart new file mode 100644 index 00000000..8bcd9a2e --- /dev/null +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/provider.dart @@ -0,0 +1,7 @@ +//@formatter:off +import 'package:get_it/get_it.dart'; +//{imports end} + +void registerProvider(GetIt getIt) { + //{provider end} +} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/remote.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/remote.dart index 83615beb..56499e9f 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/remote.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/remote.dart @@ -1,26 +1,23 @@ //@formatter:off import 'package:get_it/get_it.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/api_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_client_module.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_const.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor.dart'; -{{#graphql}}import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/graph_ql_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor_impl.dart';{{/graphql}} +import 'package:{{project_name}}/core/arch/data/remote/dio/dio_const.dart'; +{{#graphql}}import 'package:{{project_name}}/core/arch/data/remote/graph_ql/graph_ql_client.dart'; +import 'package:{{project_name}}/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor.dart'; +import 'package:{{project_name}}/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor_impl.dart';{{/graphql}} {{#firebase_auth}}import 'package:firebase_auth/firebase_auth.dart';{{/firebase_auth}} -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/api_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_client_module.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_const.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; void registerRemote(GetIt getIt) { final dioClientModule = _DioClientModule(); getIt ..registerLazySingleton( - dioClientModule.makeDioErrorHandler, - ) - ..registerLazySingleton( - () => dioClientModule.makeApiClient(DioConst.defaultBaseUrl), + dioClientModule.makeDioRequestProcessor, + )..registerLazySingleton( + () => dioClientModule.makeApiClient( + ApiClientParams( + baseUrl: DioConst.defaultBaseUrl, + ), + ), instanceName: DioConst.defaultApiClientName, ); {{#firebase_auth}} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/riverpod.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/riverpod.dart new file mode 100644 index 00000000..e9f0c2d5 --- /dev/null +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/riverpod.dart @@ -0,0 +1,8 @@ +//@formatter:off +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:get_it/get_it.dart'; +//{imports end} + +void registerRiverpod(GetIt getIt) { + //{riverpod end} +} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/source.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/source.dart index 30854c3f..74bcdf2a 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/source.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/di/source.dart @@ -1,16 +1,14 @@ //@formatter:off import 'package:get_it/get_it.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/api_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_const.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor.dart'; -{{#graphql}}import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/graph_ql_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor.dart'; +import 'package:{{project_name}}/core/arch/data/remote/dio/dio_const.dart'; +{{#graphql}}import 'package:{{project_name}}/core/arch/data/remote/graph_ql/graph_ql_client.dart'; +import 'package:{{project_name}}/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor.dart'; import 'package:{{project_name}}/data/source/remote/auth/auth_source.dart'; import 'package:{{project_name}}/data/source/remote/auth/auth_source_impl.dart';{{/graphql}} {{#firebase_auth}}import 'package:firebase_auth/firebase_auth.dart'; import 'package:{{project_name}}/data/source/remote/firebase/auth/firebase_auth_source.dart'; import 'package:{{project_name}}/data/source/remote/firebase/auth/firebase_auth_source_impl.dart';{{/firebase_auth}} - +import 'package:onix_flutter_core/onix_flutter_core.dart'; //{imports end} void registerSources(GetIt getIt) { diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/mapper/authentication/authentication_mapper.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/mapper/authentication/authentication_mapper.dart index 94c04056..0839d9a9 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/mapper/authentication/authentication_mapper.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/mapper/authentication/authentication_mapper.dart @@ -1,6 +1,6 @@ -import 'package:{{project_name}}/core/arch/domain/common/converter/mapper.dart'; import 'package:{{project_name}}/data/model/remote/authentication/authentication_response.dart'; import 'package:{{project_name}}/domain/entity/authentication/authentication.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; class _ResponseToEntity implements Mapper { diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/repository/firebase_auth_repository_impl.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/repository/firebase_auth_repository_impl.dart index 36d21f7d..4ccce165 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/repository/firebase_auth_repository_impl.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/repository/firebase_auth_repository_impl.dart @@ -1,12 +1,10 @@ -import 'package:{{project_name}}/core/arch/domain/entity/common/operation_status.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/result.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/failure/api_failure.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/failure/firebase_failure.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; +import 'package:onix_flutter_core_models/onix_flutter_core_models.dart'; import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; import 'package:{{project_name}}/data/source/remote/firebase/auth/firebase_auth_source.dart'; +import 'package:{{project_name}}/domain/entity/failure/firebase_failure.dart'; import 'package:{{project_name}}/domain/params/create_user/create_account_params.dart'; import 'package:{{project_name}}/domain/repository/firebase_auth_repository.dart'; - //{entities_imports} class FirebaseAuthRepositoryImpl extends FirebaseAuthRepository { diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/repository/refresh_token_repository_impl.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/repository/refresh_token_repository_impl.dart index 89d24f58..cfd4155d 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/repository/refresh_token_repository_impl.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/repository/refresh_token_repository_impl.dart @@ -1,4 +1,4 @@ -import 'package:{{project_name}}/core/arch/domain/entity/common/result.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; import 'package:{{project_name}}/domain/entity/authentication/authentication.dart'; import 'package:{{project_name}}/domain/repository/refresh_token_repository.dart'; diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/local/preferences_source/preferences_source_impl.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/local/preferences_source/preferences_source_impl.dart index 5a47745c..fd1b6b99 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/local/preferences_source/preferences_source_impl.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/local/preferences_source/preferences_source_impl.dart @@ -1,5 +1,4 @@ -import 'package:{{project_name}}/core/arch/data/local/prefs/base_preferences.dart'; - +import 'package:onix_flutter_core/onix_flutter_core.dart'; import 'package:{{project_name}}/data/source/local/preferences_source/preferences_keys.dart'; import 'package:{{project_name}}/data/source/local/preferences_source/preferences_source.dart'; diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/auth/auth_source.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/auth/auth_source.dart index bc1f942a..9886a594 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/auth/auth_source.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/auth/auth_source.dart @@ -1,4 +1,4 @@ -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; import 'package:{{project_name}}/data/model/remote/authentication/authentication_request.dart'; import 'package:{{project_name}}/data/model/remote/customer_access_token/customer_token_response_data.dart'; diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/auth/auth_source_impl.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/auth/auth_source_impl.dart index 01d98078..2b6b06cd 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/auth/auth_source_impl.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/auth/auth_source_impl.dart @@ -1,10 +1,10 @@ -import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/graph_ql_client.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/graph_ql/request_processor/graph_ql_request_processor.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; +import 'package:{{project_name}}/core/arch/data/remote/graph_ql/graph_ql_client.dart'; +import 'package:{{project_name}}/core/arch/data/remote/graph_ql/request_processor/graph_ql_request_processor.dart'; import 'package:{{project_name}}/data/model/remote/authentication/authentication_request.dart'; import 'package:{{project_name}}/data/model/remote/customer_access_token/customer_token_response_data.dart'; import 'package:{{project_name}}/data/source/remote/auth/auth_source.dart'; import 'package:{{project_name}}/data/source/remote/auth/mutations/access_token_mutation.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; class AuthSourceImpl extends AuthSource { final GraphQlClient _apiClient; diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/auth/firebase_auth_source.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/auth/firebase_auth_source.dart index 440c2037..287d7298 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/auth/firebase_auth_source.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/auth/firebase_auth_source.dart @@ -1,5 +1,4 @@ -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/operation_status.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; //{response_imports} //{request_imports} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/auth/firebase_auth_source_impl.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/auth/firebase_auth_source_impl.dart index 73151354..3e9d7e79 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/auth/firebase_auth_source_impl.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/auth/firebase_auth_source_impl.dart @@ -1,7 +1,5 @@ import 'package:firebase_auth/firebase_auth.dart'; - -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/operation_status.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; import 'package:{{project_name}}/data/source/remote/firebase/auth/firebase_auth_source.dart'; //{response_imports} @@ -70,7 +68,7 @@ class FirebaseAuthSourceImpl extends FirebaseAuthSource { return const DataResponse.unauthorized(); } } on FirebaseAuthException catch (e) { - return DataResponse.firebaseError(e.code); + return DataResponse.undefinedError(e); } catch (e) { return DataResponse.undefinedError(e); } diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/firebase_const.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/firebase_const.dart index 1518b5f3..19d53802 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/firebase_const.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/data/source/remote/firebase/firebase_const.dart @@ -3,4 +3,6 @@ class FirebaseConst { static const errWrongPassword = 'wrong-password'; static const errWeakPassword = 'weak-password'; static const errEmailAlreadyRegistered = 'email-already-in-use'; + + const FirebaseConst._(); } diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/firebase_failure.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/entity/failure/firebase_failure.dart similarity index 50% rename from bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/firebase_failure.dart rename to bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/entity/failure/firebase_failure.dart index a1399c26..8a1d8124 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/core/arch/domain/entity/failure/firebase_failure.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/entity/failure/firebase_failure.dart @@ -1,6 +1,6 @@ -import 'package:{{project_name}}/core/arch/domain/entity/failure/failure.dart'; +import 'package:onix_flutter_core_models/onix_flutter_core_models.dart'; -class FirebaseFailure implements FeatureFailure { +class FirebaseFailure implements Failure { FirebaseFailure(this.code); final String code; @@ -9,4 +9,4 @@ class FirebaseFailure implements FeatureFailure { String toString() { return 'FirebaseFailure{code: $code}'; } -} +} \ No newline at end of file diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/repository/firebase_auth_repository.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/repository/firebase_auth_repository.dart index a2252462..a5520b0a 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/repository/firebase_auth_repository.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/repository/firebase_auth_repository.dart @@ -1,4 +1,4 @@ -import 'package:{{project_name}}/core/arch/domain/entity/common/result.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; import 'package:{{project_name}}/domain/params/create_user/create_account_params.dart'; //{entities_imports} diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/repository/refresh_token_repository.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/repository/refresh_token_repository.dart index de2e708f..08f26042 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/repository/refresh_token_repository.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/repository/refresh_token_repository.dart @@ -1,4 +1,4 @@ -import 'package:{{project_name}}/core/arch/domain/entity/common/result.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; import 'package:{{project_name}}/domain/entity/authentication/authentication.dart'; abstract class RefreshTokenRepository { diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/create_account_use_case.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/create_account_use_case.dart index 4b9bd743..375825ff 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/create_account_use_case.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/create_account_use_case.dart @@ -1,5 +1,5 @@ +import 'package:onix_flutter_core/onix_flutter_core.dart'; import 'package:{{project_name}}/app/service/firebase_session_service/firebase_session_service.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/result.dart'; import 'package:{{project_name}}/domain/params/create_user/create_account_params.dart'; import 'package:{{project_name}}/domain/repository/firebase_auth_repository.dart'; diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/log_out_use_case.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/log_out_use_case.dart index 472a16df..0c5ab0a5 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/log_out_use_case.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/log_out_use_case.dart @@ -1,5 +1,5 @@ +import 'package:onix_flutter_core/onix_flutter_core.dart'; import 'package:{{project_name}}/app/service/firebase_session_service/firebase_session_service.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/result.dart'; import 'package:{{project_name}}/domain/repository/firebase_auth_repository.dart'; class LogOutUseCase { diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/login_use_case.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/login_use_case.dart index 5e9184a6..4a0225cb 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/login_use_case.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/domain/usecase/login_use_case.dart @@ -1,6 +1,5 @@ +import 'package:onix_flutter_core/onix_flutter_core.dart'; import 'package:{{project_name}}/app/service/firebase_session_service/firebase_session_service.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/result.dart'; - import 'package:{{project_name}}/domain/repository/firebase_auth_repository.dart'; class LoginUseCase { diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/main.gen.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/main.gen.dart index 6300e3af..c22ff4f9 100644 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/main.gen.dart +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/lib/main.gen.dart @@ -2,14 +2,16 @@ import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; +{{#isBloc}}import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart';{{/isBloc}} +{{#isRiverpod}}import 'package:flutter_riverpod/flutter_riverpod.dart';{{/isRiverpod}} import 'package:{{project_name}}/app/banned_app.dart'; -import 'package:{{project_name}}/core/arch/bloc/app_bloc_observer.dart'; import 'package:{{project_name}}/app/app.dart'; import 'package:{{project_name}}/app/app_initialization.dart'; import 'package:{{project_name}}/core/di/services.dart'; import 'package:{{project_name}}/app/util/extension/orientation_extension.dart'; import 'package:{{project_name}}/core/arch/logger/app_logger_impl.dart'; +{{#sentry}}import 'package:sentry_flutter/sentry_flutter.dart';{{/sentry}} Future main{{#flavorizr}}App{{/flavorizr}}() async { unawaited( @@ -17,23 +19,37 @@ Future main{{#flavorizr}}App{{/flavorizr}}() async { () async { WidgetsFlutterBinding.ensureInitialized(); await Initialization.I.initApp(); - + {{#sentry}}await SentryFlutter.init( + (options) { + options.dsn = 'SENTRY_DSN'; + }, + );{{/sentry}} await OrientationExtension.lockVertical(); - Bloc.observer = AppBlocObserver(); + {{#isBloc}}Bloc.observer = AppBlocObserver();{{/isBloc}} final isAllowedToUseApp = await environmentService().initialize(); if (isAllowedToUseApp) { + {{#isRiverpod}} + runApp(const ProviderScope(child: App())); + {{/isRiverpod}} + {{^isRiverpod}} runApp(const App()); + {{/isRiverpod}} } else { runApp(const BannedApp()); } }, - (error, stackTrace) { - logger.crash(error: error, stackTrace: stackTrace, reason: 'main'); - }, - )?.catchError((e, trace) { - logger.crash(error: e, stackTrace: trace, reason: 'main'); + _onError, + )?.catchError((error, stackTrace) { + _onError(error, stackTrace); exit(-1); - }), + }, + ), ); +} + + +Future _onError(dynamic error, dynamic stackTrace) async { + logger.crash(error: error, stackTrace: stackTrace, reason: 'main'); + {{#sentry}}await Sentry.captureException(error, stackTrace: stackTrace);{{/sentry}} } \ No newline at end of file diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/test/app_test.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/test/app_test.dart new file mode 100644 index 00000000..05a37e98 --- /dev/null +++ b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/test/app_test.dart @@ -0,0 +1 @@ +void main() {} \ No newline at end of file diff --git a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/test/core/data/remote/dio/dio_request_processor/dio_request_processor_impl_test.dart b/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/test/core/data/remote/dio/dio_request_processor/dio_request_processor_impl_test.dart deleted file mode 100644 index 06128ec1..00000000 --- a/bricks/flutter_clean_base/__brick__/{{project_name.snakeCase()}}/test/core/data/remote/dio/dio_request_processor/dio_request_processor_impl_test.dart +++ /dev/null @@ -1,503 +0,0 @@ -import 'package:{{project_name}}/core/arch/data/remote/base/http_status.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor.dart'; -import 'package:{{project_name}}/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor_impl.dart'; -import 'package:{{project_name}}/core/arch/data/remote/error/default_api_error.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/data_response.dart'; -import 'package:{{project_name}}/core/arch/domain/entity/common/operation_status.dart'; -import 'package:connectivity_plus/connectivity_plus.dart'; -import 'package:dio/dio.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:internet_connection_checker/internet_connection_checker.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'dio_request_processor_impl_test.mocks.dart'; - -class _MockedException implements Exception { - const _MockedException(); -} - -const mockedException = _MockedException(); - -@GenerateNiceMocks([ - MockSpec(), - MockSpec(), -]) -void main() { - group('DataResponse error tests', () { - late DioRequestProcessor requestProcessor; - - setUp(() { - requestProcessor = DioRequestProcessorImpl(); - }); - - test('DataResponse.undefinedError with non DioExceptionType case', - () async { - Future mockedRequest() { - throw mockedException; - } - - final result = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result, - const DataResponse.undefinedError(mockedException), - ); - }); - - test('DioExceptionType.connectionTimeout case', () async { - Future mockedRequest() { - throw DioException( - type: DioExceptionType.connectionTimeout, - message: '', - requestOptions: RequestOptions(), - error: '', - ); - } - - final result = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result, - const DataResponse.notConnected(), - ); - }); - - test('DioExceptionType.sendTimeout case', () async { - Future mockedRequest() { - throw DioException( - type: DioExceptionType.sendTimeout, - message: '', - requestOptions: RequestOptions(), - error: '', - ); - } - - final result = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result, - const DataResponse.notConnected(), - ); - }); - - test('HttpStatus.networkConnectTimeoutError case', () async { - Future mockedRequest() { - throw DioException( - message: '', - requestOptions: RequestOptions(), - response: Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.networkConnectTimeoutError, - ), - error: '', - ); - } - - final result = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result, - const DataResponse.notConnected(), - ); - }); - - test('HttpStatus.unauthorized case', () async { - Future mockedRequest() { - throw DioException( - message: '', - requestOptions: RequestOptions(), - response: Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.unauthorized, - ), - error: '', - ); - } - - final result = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result, - const DataResponse.unauthorized(), - ); - }); - - test('HttpStatus.tooManyRequests case', () async { - Future mockedRequest() { - throw DioException( - message: '', - requestOptions: RequestOptions(), - response: Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.tooManyRequests, - ), - error: '', - ); - } - - final result = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result, - const DataResponse.tooManyRequests(), - ); - }); - - test('HttpStatus.badRequest case', () async { - final exception = DioException( - message: '', - requestOptions: RequestOptions(), - response: Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.badRequest, - data: { - 'name': 'name', - 'code': 'code', - }, - ), - error: '', - ); - - Future mockedRequest() { - throw exception; - } - - final result = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result, - const DataResponse.apiError( - DefaultApiError( - name: 'name', - code: 'code', - ), - HttpStatus.badRequest, - ), - ); - }); - - test('Empty response body case', () async { - final mockedException = DioException( - message: '', - requestOptions: RequestOptions(), - response: Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.badRequest, - ), - error: '', - ); - - Future mockedRequest() { - throw mockedException; - } - - final result = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result, - DataResponse.undefinedError( - mockedException, - HttpStatus.badRequest, - ), - ); - }); - - test('Unexpected ResponseType case', () async { - final mockedException = DioException( - message: '', - requestOptions: RequestOptions(), - response: Response( - requestOptions: RequestOptions( - responseType: ResponseType.plain, - ), - statusCode: HttpStatus.badRequest, - data: '', - ), - error: '', - ); - - Future mockedRequest() { - throw mockedException; - } - - final result = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result, - DataResponse.undefinedError(mockedException), - ); - }); - - test('HttpStatus.internalServerError case', () async { - final mockedException = DioException( - message: '', - requestOptions: RequestOptions(), - response: Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.internalServerError, - ), - error: '', - ); - - Future mockedRequest() { - throw mockedException; - } - - final result1 = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result1, - DataResponse.undefinedError( - mockedException, - HttpStatus.internalServerError, - ), - ); - }); - - test('HttpStatus.serviceUnavailable case', () async { - final mockedException = DioException( - message: '', - requestOptions: RequestOptions(), - response: Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.serviceUnavailable, - ), - error: '', - ); - - Future mockedRequest() { - throw mockedException; - } - - final result1 = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result1, - DataResponse.undefinedError( - mockedException, - HttpStatus.serviceUnavailable, - ), - ); - }); - - test('HttpStatus.forbidden case', () async { - final mockedException = DioException( - message: '', - requestOptions: RequestOptions(), - response: Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.forbidden, - ), - error: '', - ); - - Future mockedRequest() { - throw mockedException; - } - - final result1 = - await requestProcessor.processRequest( - onRequest: mockedRequest, - onResponse: (_) => OperationStatus.success, - ); - - expect( - result1, - DataResponse.undefinedError( - mockedException, - HttpStatus.forbidden, - ), - ); - }); - - test('Request is cancelled', () async { - final cancelToken = CancelToken(); - final fetchDataFuture = Dio().get( - 'https://jsonplaceholder.typicode.com/posts', - cancelToken: cancelToken, - ); - cancelToken.cancel('Cancelled by user'); - try { - await fetchDataFuture; - fail('Expected DioError to be thrown'); - } catch (e) { - expect(e, isA()); - expect((e as DioException).type, DioExceptionType.cancel); - expect(e.error, 'Cancelled by user'); - } - }); - - test('Request is cancelled and DataResponse.requestCanceled returned', - () async { - final cancelToken = CancelToken(); - final fetchDataFuture = Dio().get( - 'https://jsonplaceholder.typicode.com/posts', - cancelToken: cancelToken, - ); - cancelToken.cancel('Cancelled by user'); - - final result = await requestProcessor.processRequest( - onRequest: () => fetchDataFuture, - onResponse: (e) {}, - ); - - final failure = result.maybeWhen( - canceledRequest: () => true, - orElse: () => false, - ); - - expect(result.isError(), true); - expect(failure, true); - }); - }); - - group('HttpStatus.kCodeSuccess tests', () { - late DioRequestProcessor requestProcessor; - - setUp(() { - requestProcessor = DioRequestProcessorImpl(); - }); - - test('Success case', () async { - const mockedData = 'test'; - - Future> mockedRequest() { - return Future>.value( - Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.kCodeSuccess200, - data: mockedData, - ), - ); - } - - final result = - await requestProcessor.processRequest, String>( - onRequest: mockedRequest, - onResponse: (response) => response.data as String, - ); - - expect(result, const DataResponse.success(mockedData)); - }); - }); - - group('Connectivity && InternetConnectionChecker tests', () { - late DioRequestProcessor requestProcessor; - late Connectivity connectivity; - late InternetConnectionChecker internetConnectionChecker; - - setUp(() { - connectivity = MockConnectivity(); - internetConnectionChecker = MockInternetConnectionChecker(); - requestProcessor = DioRequestProcessorImpl( - connectivity: connectivity, - internetConnectionChecker: internetConnectionChecker, - ); - }); - - test('ConnectivityResult.none test', () async { - const mockedData = 'test'; - - when(connectivity.checkConnectivity()).thenAnswer( - (_) async => [ConnectivityResult.none], - ); - - when(internetConnectionChecker.hasConnection).thenAnswer( - (_) async => false, - ); - - Future> mockedRequest() { - return Future>.value( - Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.kCodeSuccess200, - data: mockedData, - ), - ); - } - - final result = - await requestProcessor.processRequest, String>( - onRequest: mockedRequest, - onResponse: (response) => response.data as String, - ); - - expect(result, const DataResponse.notConnected()); - }); - - test('ConnectivityResult.mobile && hasConnection test', () async { - const mockedData = 'test'; - - when(connectivity.checkConnectivity()).thenAnswer( - (_) async => [ConnectivityResult.mobile], - ); - - when(internetConnectionChecker.hasConnection).thenAnswer( - (_) async => true, - ); - - Future> mockedRequest() { - return Future>.value( - Response( - requestOptions: RequestOptions(), - statusCode: HttpStatus.kCodeSuccess200, - data: mockedData, - ), - ); - } - - final result = - await requestProcessor.processRequest, String>( - onRequest: mockedRequest, - onResponse: (response) => response.data as String, - ); - - expect(result, const DataResponse.success(mockedData)); - }); - }); -} diff --git a/bricks/flutter_clean_base/hooks/post_gen.dart b/bricks/flutter_clean_base/hooks/post_gen.dart index 229a1b53..29988189 100644 --- a/bricks/flutter_clean_base/hooks/post_gen.dart +++ b/bricks/flutter_clean_base/hooks/post_gen.dart @@ -133,40 +133,22 @@ Future getDependencies(HookContext context) async { List dependencies = [ 'cupertino_icons', 'dio', - 'pretty_dio_logger', - 'dio_cache_interceptor', - 'dio_cache_interceptor_hive_store', 'hive_flutter', 'freezed_annotation', 'json_annotation', 'get_it', - 'flutter_bloc', 'flutter_secure_storage:^9.0.0', 'shared_preferences', - 'internet_connection_checker', - 'retry', - 'encrypt', 'path_provider', 'logger', 'fluttertoast', 'collection', 'flutter_dotenv', - 'flutter_jailbreak_detection', + 'jailbreak_root_detection', 'gap', - // (Ivan Modlo): Connectivity Service has been blocked due to - // unit tests that differ from the major version are lower than 6 - 'connectivity_plus: ^6.0.3', + 'onix_flutter_core', ]; - if (!context.vars['web_only']) { - if (context.vars['screen_util']) { - dependencies.add('flutter_screenutil'); - } - dependencies.add('loader_overlay'); - } else { - dependencies.add('flutter_overlay_loader'); - } - List devDependencies = [ 'flutter_lints', 'build_runner', @@ -174,10 +156,44 @@ Future getDependencies(HookContext context) async { 'json_serializable', 'import_sorter', 'mockito', - 'bloc_test', 'test', ]; + if (context.vars['isBloc']) { + dependencies.addAll(['flutter_bloc', 'onix_flutter_bloc']); + devDependencies.add('bloc_test'); + await removeStateManagers(managers: ['provider', 'riverpod']); + } + + if (context.vars['isProvider']) { + dependencies.addAll(['provider', 'onix_flutter_provider']); + await removeStateManagers(managers: ['bloc', 'riverpod']); + } + + if (context.vars['isRiverpod']) { + dependencies.add('flutter_riverpod'); + await removeStateManagers(managers: ['bloc', 'provider']); + } + + if (context.vars['isBase']) { + await removeStateManagers(managers: ['provider', 'bloc', 'riverpod']); + } else { + dependencies.add('onix_flutter_core_models'); + } + + if (!context.vars['web_only']) { + if (context.vars['screen_util']) { + dependencies.add('flutter_screenutil'); + } + dependencies.add('loader_overlay'); + } else { + dependencies.add('flutter_overlay_loader'); + } + + if (context.vars['sentry']) { + dependencies.add('sentry_flutter'); + } + if (context.vars['theme_generate']) { dependencies.add('theme_tailor_annotation:3.0.1'); devDependencies.add('theme_tailor:3.0.1'); @@ -267,6 +283,13 @@ Future getDependencies(HookContext context) async { } } +Future removeStateManagers({required List managers}) async { + for (var manager in managers) { + await Process.run('rm', ['$manager.dart'], + workingDirectory: '$name/lib/core/di'); + } +} + Future flavorize(HookContext context) async { 'Flavorizing...'.log(); @@ -483,6 +506,24 @@ flutter_additional_ios_build_settings(target) 11.0''', ''' MinimumOSVersion 12.0''')); + File mainInfoPlistFile = File('$name/ios/Runner/Info.plist'); + String mainInfoPlistFileContent = mainInfoPlistFile.readAsStringSync(); + + mainInfoPlistFileContent = mainInfoPlistFileContent.replaceAll(''' +''', '''LSApplicationQueriesSchemes + + undecimus + sileo + zbra + filza + activator + cydia + + +'''); + + mainInfoPlistFile.writeAsStringSync(mainInfoPlistFileContent); + File xcodeWorkspaceFile = File('$name/ios/Runner.xcodeproj/project.pbxproj'); List xcodeWorkspaceFileContent = diff --git a/bricks/flutter_clean_base/hooks/pre_gen.dart b/bricks/flutter_clean_base/hooks/pre_gen.dart index 9ba61a7c..68f28386 100644 --- a/bricks/flutter_clean_base/hooks/pre_gen.dart +++ b/bricks/flutter_clean_base/hooks/pre_gen.dart @@ -56,6 +56,13 @@ Future> _initCustomVars(HookContext context) async { final localizationByHand = context.vars['localization'] == 'flutter_gen' ? true : false; + final isBase = context.vars['state_management'] == 'base' ? true : false; + final isBloc = context.vars['state_management'] == 'bloc' ? true : false; + final isProvider = + context.vars['state_management'] == 'provider' ? true : false; + final isRiverpod = + context.vars['state_management'] == 'riverpod' ? true : false; + var flavors = []; if (context.vars['flavorizr'] == true) { @@ -82,6 +89,11 @@ Future> _initCustomVars(HookContext context) async { 'project_name': context.vars['project_name_dirt'].toString().toSnakeCase, 'web_only': context.vars['platforms'] == 'web', 'screen_util': context.vars['screen_util'], + 'isBase': isBase, + 'isBloc': isBloc, + 'isProvider': isProvider, + 'isRiverpod': isRiverpod, + 'sentry': context.vars['sentry'], }; } diff --git a/docs/HOW_TO.md b/docs/HOW_TO.md index c8dda5ed..7d377379 100644 --- a/docs/HOW_TO.md +++ b/docs/HOW_TO.md @@ -46,7 +46,7 @@ Here you can find all the base classes which that are included in the API client Base API url and API client name are located in: ``` -lib/core/arch/data/remote/clients/dio/dio_const.dart +lib/core/arch/data/remote/dio/dio_const.dart ``` You free to add as much URls you need and declare a new API clients to use with different urls. diff --git a/lib/app/app.dart b/lib/app/app.dart index f5e85f1b..12033ee4 100644 --- a/lib/app/app.dart +++ b/lib/app/app.dart @@ -2,8 +2,8 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:loader_overlay/loader_overlay.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_imports.dart'; class App extends StatefulWidget { @@ -33,13 +33,10 @@ class _AppState extends State { ); }, scrollBehavior: const CupertinoScrollBehavior(), - title: '', theme: createLightTheme(), darkTheme: createDarkTheme(), themeMode: ThemeMode.dark, - routeInformationProvider: AppRouter.router.routeInformationProvider, - routeInformationParser: AppRouter.router.routeInformationParser, - routerDelegate: AppRouter.router.routerDelegate, + routerConfig: AppRouter.router, locale: locale, localizationsDelegates: const [ S.delegate, diff --git a/lib/core/app/app_consts.dart b/lib/app/app_consts.dart similarity index 89% rename from lib/core/app/app_consts.dart rename to lib/app/app_consts.dart index cdea61a4..9219436a 100644 --- a/lib/core/app/app_consts.dart +++ b/lib/app/app_consts.dart @@ -1,4 +1,4 @@ -abstract final class AppConsts { +class AppConsts { static const String releaseUri = 'https://github.com/Onix-Systems/onix-flutter-project-generator/releases'; @@ -43,4 +43,10 @@ abstract final class AppConsts { static RegExp organizationInputRegExp = RegExp('[a-z0-9.]'); static RegExp projectNameInputRegExp = RegExp('[a-z0-9_]'); + + static RegExp digitsAndLatinWithSpaceOnly = RegExp(r'[a-zA-Z\d ]'); + + static RegExp digitsAndLatinLetters = RegExp('[a-zA-Z0-9]'); + + const AppConsts._(); } diff --git a/lib/core/app/app_initialization.dart b/lib/app/app_initialization.dart similarity index 100% rename from lib/core/app/app_initialization.dart rename to lib/app/app_initialization.dart diff --git a/lib/core/extension/logger_extension.dart b/lib/app/extension/logger_extension.dart similarity index 100% rename from lib/core/extension/logger_extension.dart rename to lib/app/extension/logger_extension.dart diff --git a/lib/core/extension/ui_utils_extension.dart b/lib/app/extension/ui_utils_extension.dart similarity index 100% rename from lib/core/extension/ui_utils_extension.dart rename to lib/app/extension/ui_utils_extension.dart diff --git a/lib/core/app/localization/generated/intl/messages_all.dart b/lib/app/localization/generated/intl/messages_all.dart similarity index 100% rename from lib/core/app/localization/generated/intl/messages_all.dart rename to lib/app/localization/generated/intl/messages_all.dart diff --git a/lib/core/app/localization/generated/intl/messages_en.dart b/lib/app/localization/generated/intl/messages_en.dart similarity index 92% rename from lib/core/app/localization/generated/intl/messages_en.dart rename to lib/app/localization/generated/intl/messages_en.dart index 0dc6ff94..f59e04fc 100644 --- a/lib/core/app/localization/generated/intl/messages_en.dart +++ b/lib/app/localization/generated/intl/messages_en.dart @@ -20,22 +20,25 @@ typedef String MessageIfAbsent(String messageStr, List args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'en'; - static String m0(componentName) => "${componentName} component preview"; + static String m0(variant) => + "Changing state manager will change ... to ${variant}. Are you sure you want to continue?"; - static String m1(componentName) => + static String m1(componentName) => "${componentName} component preview"; + + static String m2(componentName) => "Data component ${componentName} already exists"; - static String m2(sourceName) => " in ${sourceName} source"; + static String m3(sourceName) => " in ${sourceName} source"; - static String m3(componentName) => + static String m4(componentName) => "Do you really want to delete component ${componentName}?"; - static String m4(projectName) => "Modify ${projectName}"; + static String m5(projectName) => "Modify ${projectName}"; - static String m5(sourceName) => + static String m6(sourceName) => "Do you really want to delete source ${sourceName}?"; - static String m6(sourceName) => "${sourceName}Source already exists"; + static String m7(sourceName) => "${sourceName}Source already exists"; final messages = _notInlinedMessages(_notInlinedMessages); static Map _notInlinedMessages(_) => { @@ -57,6 +60,9 @@ class MessageLookup extends MessageLookupByLibrary { "apiFailureUndefined": MessageLookupByLibrary.simpleMessage( "Uh oh! Looks like we ran into an issue while processing this request. Please try again.\n\nReach out to support if you continue to experience issues."), "cancel": MessageLookupByLibrary.simpleMessage("Cancel"), + "changeStateManagerError": MessageLookupByLibrary.simpleMessage( + "Change state manager warning"), + "changeStateManagerErrorContent": m0, "checkNamesContentFirstPart": MessageLookupByLibrary.simpleMessage("Is project name\n"), "checkNamesContentLastPart": @@ -71,19 +77,19 @@ class MessageLookup extends MessageLookupByLibrary { "colorStyles": MessageLookupByLibrary.simpleMessage("Color Styles"), "componentNamePlaceholder": MessageLookupByLibrary.simpleMessage("Component name"), - "componentPreview": m0, + "componentPreview": m1, "continueLabel": MessageLookupByLibrary.simpleMessage("Continue"), "createRequestCheckboxLabel": MessageLookupByLibrary.simpleMessage("Create request?"), "createResponseCheckboxLabel": MessageLookupByLibrary.simpleMessage("Create response?"), "dataComponent": MessageLookupByLibrary.simpleMessage("Data component"), - "dataComponentExistsError": m1, - "dataComponentExistsInSource": m2, + "dataComponentExistsError": m2, + "dataComponentExistsInSource": m3, "dataComponents": MessageLookupByLibrary.simpleMessage("Data components"), "delete": MessageLookupByLibrary.simpleMessage("Delete"), - "deleteComponentConfirmation": m3, + "deleteComponentConfirmation": m4, "dialogWillOpenInSeparateWindow": MessageLookupByLibrary.simpleMessage( "(Dialog will open in separate window)"), "emptyConfigContent": MessageLookupByLibrary.simpleMessage( @@ -139,16 +145,16 @@ class MessageLookup extends MessageLookupByLibrary { MessageLookupByLibrary.simpleMessage("Import REST API requests"), "importStyles": MessageLookupByLibrary.simpleMessage("Import Styles"), "initial": MessageLookupByLibrary.simpleMessage("Initial screen?"), - "integrateDevicePreview": - MessageLookupByLibrary.simpleMessage("Integrate Device Preview?"), "integrateGraphQl": MessageLookupByLibrary.simpleMessage("Integrate GraphQL?"), + "integrateSentry": + MessageLookupByLibrary.simpleMessage("Integrate Sentry?"), "keyStorePasswordPlaceholder": MessageLookupByLibrary.simpleMessage("Leave blank to auto-gen..."), "keystorePassword": MessageLookupByLibrary.simpleMessage(" Keystore password"), "list": MessageLookupByLibrary.simpleMessage("List"), - "localization": MessageLookupByLibrary.simpleMessage("Localization:"), + "localization": MessageLookupByLibrary.simpleMessage("Localization"), "localizationMethod": MessageLookupByLibrary.simpleMessage("Localization method"), "masonBrickSource": @@ -156,7 +162,7 @@ class MessageLookup extends MessageLookupByLibrary { "modify": MessageLookupByLibrary.simpleMessage("Modify"), "modifyComponent": MessageLookupByLibrary.simpleMessage("Modify component"), - "modifyGeneratedProject": m4, + "modifyGeneratedProject": m5, "modifyScreen": MessageLookupByLibrary.simpleMessage("Modify screen"), "modifySigningVars": MessageLookupByLibrary.simpleMessage("Modify signing vars..."), @@ -204,11 +210,13 @@ class MessageLookup extends MessageLookupByLibrary { "request": MessageLookupByLibrary.simpleMessage("Request"), "response": MessageLookupByLibrary.simpleMessage("Response"), "retry": MessageLookupByLibrary.simpleMessage("Retry"), - "router": MessageLookupByLibrary.simpleMessage("Router:"), + "router": MessageLookupByLibrary.simpleMessage("Router"), "screenAlreadyExistsContent": MessageLookupByLibrary.simpleMessage( "Screen with such name already exists"), "screenAlreadyExistsTitle": MessageLookupByLibrary.simpleMessage("Already exists"), + "screenClassNameHelperText": MessageLookupByLibrary.simpleMessage( + "The first character in the class name must be a letter"), "screenName": MessageLookupByLibrary.simpleMessage("Screen name"), "screens": MessageLookupByLibrary.simpleMessage("Screens"), "selectProjectFolder": @@ -230,8 +238,8 @@ class MessageLookup extends MessageLookupByLibrary { "signingToolTitle": MessageLookupByLibrary.simpleMessage( "Android signing configuration"), "signingVars": MessageLookupByLibrary.simpleMessage("Signing vars"), - "sourceDeletingDialogTitle": m5, - "sourceExistsError": m6, + "sourceDeletingDialogTitle": m6, + "sourceExistsError": m7, "sourceNamePlaceholder": MessageLookupByLibrary.simpleMessage("Source name"), "sources": MessageLookupByLibrary.simpleMessage("Sources"), diff --git a/lib/core/app/localization/generated/intl/messages_uk.dart b/lib/app/localization/generated/intl/messages_uk.dart similarity index 92% rename from lib/core/app/localization/generated/intl/messages_uk.dart rename to lib/app/localization/generated/intl/messages_uk.dart index 29bdd963..dc5490a8 100644 --- a/lib/core/app/localization/generated/intl/messages_uk.dart +++ b/lib/app/localization/generated/intl/messages_uk.dart @@ -20,21 +20,24 @@ typedef String MessageIfAbsent(String messageStr, List args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'uk'; - static String m0(componentName) => "Перегляд компонента ${componentName}"; + static String m0(variant) => + "Зміна стейт мененджера змінить ... на ${variant}. Дійсно бажаєте продовжити?"; - static String m1(componentName) => "Компонент ${componentName} вже існує"; + static String m1(componentName) => "Перегляд компонента ${componentName}"; - static String m2(sourceName) => " в джерелі ${sourceName}"; + static String m2(componentName) => "Компонент ${componentName} вже існує"; - static String m3(componentName) => + static String m3(sourceName) => " в джерелі ${sourceName}"; + + static String m4(componentName) => "Дійсно хочете видалити компонент ${componentName}?"; - static String m4(projectName) => "Змінити ${projectName}"; + static String m5(projectName) => "Змінити ${projectName}"; - static String m5(sourceName) => + static String m6(sourceName) => "Дійсно хочете видалити джерело ${sourceName}?"; - static String m6(sourceName) => "${sourceName}Source вже існує"; + static String m7(sourceName) => "${sourceName}Source вже існує"; final messages = _notInlinedMessages(_notInlinedMessages); static Map _notInlinedMessages(_) => { @@ -58,6 +61,9 @@ class MessageLookup extends MessageLookupByLibrary { "apiFailureUndefined": MessageLookupByLibrary.simpleMessage( "Ой! Схоже, що в нас проблема з цим запитом. Будь ласка, спробуйте ще раз.\n\nЯкщо проблема не вирішилась - зверніться до техпідтримки."), "cancel": MessageLookupByLibrary.simpleMessage("Відміна"), + "changeStateManagerError": MessageLookupByLibrary.simpleMessage( + "Попередження зміни стейт менеджера"), + "changeStateManagerErrorContent": m0, "checkNamesContentFirstPart": MessageLookupByLibrary.simpleMessage("Назва проекту\n"), "checkNamesContentLastPart": @@ -72,7 +78,7 @@ class MessageLookup extends MessageLookupByLibrary { "colorStyles": MessageLookupByLibrary.simpleMessage("Кольори"), "componentNamePlaceholder": MessageLookupByLibrary.simpleMessage("Назва компонента"), - "componentPreview": m0, + "componentPreview": m1, "continueLabel": MessageLookupByLibrary.simpleMessage("Продовжити"), "createRequestCheckboxLabel": MessageLookupByLibrary.simpleMessage("Створити запит?"), @@ -80,12 +86,12 @@ class MessageLookup extends MessageLookupByLibrary { MessageLookupByLibrary.simpleMessage("Створити відповідь?"), "dataComponent": MessageLookupByLibrary.simpleMessage("Компонент даних"), - "dataComponentExistsError": m1, - "dataComponentExistsInSource": m2, + "dataComponentExistsError": m2, + "dataComponentExistsInSource": m3, "dataComponents": MessageLookupByLibrary.simpleMessage("Компоненти даних"), "delete": MessageLookupByLibrary.simpleMessage("Видалити"), - "deleteComponentConfirmation": m3, + "deleteComponentConfirmation": m4, "dialogWillOpenInSeparateWindow": MessageLookupByLibrary.simpleMessage( "(Діалог видкріється в окремому вікні)"), "emptyConfigContent": MessageLookupByLibrary.simpleMessage( @@ -108,6 +114,8 @@ class MessageLookup extends MessageLookupByLibrary { "figmaGetStylesError": MessageLookupByLibrary.simpleMessage( "Помилка завантаження стилів: перевірте інтернет з\'єднання, id figma файлу та токен"), "figmaToken": MessageLookupByLibrary.simpleMessage("Токен Figma"), + "firebaseAuth": MessageLookupByLibrary.simpleMessage( + "Інтегрувати Firebase з FirebaseAuth?"), "firstLastName": MessageLookupByLibrary.simpleMessage(" Ім\'я та прізвище"), "flavorize": @@ -144,12 +152,14 @@ class MessageLookup extends MessageLookupByLibrary { "initial": MessageLookupByLibrary.simpleMessage("Початковий екран?"), "integrateGraphQl": MessageLookupByLibrary.simpleMessage("Інтегрувати GraphQL?"), + "integrateSentry": + MessageLookupByLibrary.simpleMessage("Інтегрувати Sentry?"), "keyStorePasswordPlaceholder": MessageLookupByLibrary.simpleMessage( "Залиште пустим для автогенерації..."), "keystorePassword": MessageLookupByLibrary.simpleMessage(" Пароль до сховища ключів"), "list": MessageLookupByLibrary.simpleMessage("Список"), - "localization": MessageLookupByLibrary.simpleMessage("Локалізація:"), + "localization": MessageLookupByLibrary.simpleMessage("Локалізація"), "localizationMethod": MessageLookupByLibrary.simpleMessage("Метод локалізації"), "masonBrickSource": @@ -157,7 +167,7 @@ class MessageLookup extends MessageLookupByLibrary { "modify": MessageLookupByLibrary.simpleMessage("Змінити"), "modifyComponent": MessageLookupByLibrary.simpleMessage("Змінити компонент"), - "modifyGeneratedProject": m4, + "modifyGeneratedProject": m5, "modifyScreen": MessageLookupByLibrary.simpleMessage("Змінити екран"), "modifySigningVars": MessageLookupByLibrary.simpleMessage("Змінити дані підпису..."), @@ -206,11 +216,13 @@ class MessageLookup extends MessageLookupByLibrary { "request": MessageLookupByLibrary.simpleMessage("Запит"), "response": MessageLookupByLibrary.simpleMessage("Відповідь"), "retry": MessageLookupByLibrary.simpleMessage("Повторити"), - "router": MessageLookupByLibrary.simpleMessage("Роутер:"), + "router": MessageLookupByLibrary.simpleMessage("Роутер"), "screenAlreadyExistsContent": MessageLookupByLibrary.simpleMessage( "Екран з такою назвою вже існує"), "screenAlreadyExistsTitle": MessageLookupByLibrary.simpleMessage("Вже є"), + "screenClassNameHelperText": MessageLookupByLibrary.simpleMessage( + "Перший символ у назві класу має бути літерою"), "screenName": MessageLookupByLibrary.simpleMessage("Назва екрану"), "screens": MessageLookupByLibrary.simpleMessage("Екрани"), "selectProjectFolder": @@ -232,8 +244,8 @@ class MessageLookup extends MessageLookupByLibrary { "signingToolTitle": MessageLookupByLibrary.simpleMessage("Сертифікат підпису Android"), "signingVars": MessageLookupByLibrary.simpleMessage("Дані підпису"), - "sourceDeletingDialogTitle": m5, - "sourceExistsError": m6, + "sourceDeletingDialogTitle": m6, + "sourceExistsError": m7, "sourceNamePlaceholder": MessageLookupByLibrary.simpleMessage("Назва джерела"), "sources": MessageLookupByLibrary.simpleMessage("Джерела"), @@ -251,7 +263,7 @@ class MessageLookup extends MessageLookupByLibrary { "Файл Свагера містить компоненти, що конфліктують з тими що є. Замінити зпарсеними компоненами або ігнорувати конфліктуючі дані?"), "swaggerURL": MessageLookupByLibrary.simpleMessage("Swagger URL"), "textStyles": MessageLookupByLibrary.simpleMessage("Стилі тексту"), - "theming": MessageLookupByLibrary.simpleMessage("Theming"), + "theming": MessageLookupByLibrary.simpleMessage("Темізація"), "title": MessageLookupByLibrary.simpleMessage( "Onix Flutter Project Generator"), "tools": MessageLookupByLibrary.simpleMessage("Інструменти"), diff --git a/lib/core/app/localization/generated/l10n.dart b/lib/app/localization/generated/l10n.dart similarity index 96% rename from lib/core/app/localization/generated/l10n.dart rename to lib/app/localization/generated/l10n.dart index 78566b1a..519c9731 100644 --- a/lib/core/app/localization/generated/l10n.dart +++ b/lib/app/localization/generated/l10n.dart @@ -490,16 +490,6 @@ class S { ); } - /// `Integrate Device Preview?` - String get integrateDevicePreview { - return Intl.message( - 'Integrate Device Preview?', - name: 'integrateDevicePreview', - desc: '', - args: [], - ); - } - /// `Theming` String get theming { return Intl.message( @@ -510,20 +500,20 @@ class S { ); } - /// `Localization:` + /// `Localization` String get localization { return Intl.message( - 'Localization:', + 'Localization', name: 'localization', desc: '', args: [], ); } - /// `Router:` + /// `Router` String get router { return Intl.message( - 'Router:', + 'Router', name: 'router', desc: '', args: [], @@ -560,6 +550,16 @@ class S { ); } + /// `Integrate Sentry?` + String get integrateSentry { + return Intl.message( + 'Integrate Sentry?', + name: 'integrateSentry', + desc: '', + args: [], + ); + } + /// `Use Screen Util?` String get useScreenUtil { return Intl.message( @@ -1519,6 +1519,36 @@ class S { args: [], ); } + + /// `Change state manager warning` + String get changeStateManagerError { + return Intl.message( + 'Change state manager warning', + name: 'changeStateManagerError', + desc: '', + args: [], + ); + } + + /// `Changing state manager will change ... to {variant}. Are you sure you want to continue?` + String changeStateManagerErrorContent(Object variant) { + return Intl.message( + 'Changing state manager will change ... to $variant. Are you sure you want to continue?', + name: 'changeStateManagerErrorContent', + desc: '', + args: [variant], + ); + } + + /// `The first character in the class name must be a letter` + String get screenClassNameHelperText { + return Intl.message( + 'The first character in the class name must be a letter', + name: 'screenClassNameHelperText', + desc: '', + args: [], + ); + } } class AppLocalizationDelegate extends LocalizationsDelegate { diff --git a/lib/core/app/localization/l10n/intl_en.arb b/lib/app/localization/l10n/intl_en.arb similarity index 89% rename from lib/core/app/localization/l10n/intl_en.arb rename to lib/app/localization/l10n/intl_en.arb index 5d7a2cf8..0bd6f7ec 100644 --- a/lib/core/app/localization/l10n/intl_en.arb +++ b/lib/app/localization/l10n/intl_en.arb @@ -44,13 +44,13 @@ "usingBloc": "Using BLoC", "usingCubit": "Using Cubit", "actions": "Actions", - "integrateDevicePreview": "Integrate Device Preview?", "theming": "Theming", - "localization": "Localization:", - "router": "Router:", + "localization": "Localization", + "router": "Router", "useSonar": "Will you use Sonar?", "firebaseAuth": "Integrate Firebase with FirebaseAuth?", "integrateGraphQl": "Integrate GraphQL?", + "integrateSentry": "Integrate Sentry?", "useScreenUtil": "Use Screen Util?", "generateSonarConfig": "Generate Sonar config?", "modifySigningVars": "Modify signing vars...", @@ -145,6 +145,9 @@ "clear": "Clear", "parseErrorMessage": "Failed to Parse Swagger Components. Please try again or contact support if issue not resolved.", "noDataComponents": "No data components", - "projectNameHelperText" : "Project name must be fully lowercase, with underscores to separate words. Also make sure that the name is a valid Dart identifier - it does not start with numbers, is not a reserved word, and does not start or end with an underscore.", - "organizationNameHelperText" : "A digit cannot be the first character in a package segment. The package must have at least one '.’ separator. Multiple '.' characters are not allowed in a row." + "projectNameHelperText": "Project name must be fully lowercase, with underscores to separate words. Also make sure that the name is a valid Dart identifier - it does not start with numbers, is not a reserved word, and does not start or end with an underscore.", + "organizationNameHelperText": "A digit cannot be the first character in a package segment. The package must have at least one '.’ separator. Multiple '.' characters are not allowed in a row.", + "changeStateManagerError": "Change state manager warning", + "changeStateManagerErrorContent": "Changing state manager will change ... to {variant}. Are you sure you want to continue?", + "screenClassNameHelperText": "The first character in the class name must be a letter" } \ No newline at end of file diff --git a/lib/core/app/localization/l10n/intl_uk.arb b/lib/app/localization/l10n/intl_uk.arb similarity index 94% rename from lib/core/app/localization/l10n/intl_uk.arb rename to lib/app/localization/l10n/intl_uk.arb index 88c20614..f206028e 100644 --- a/lib/core/app/localization/l10n/intl_uk.arb +++ b/lib/app/localization/l10n/intl_uk.arb @@ -44,11 +44,13 @@ "usingBloc": "Використати BLoC", "usingCubit": "Використати Cubit", "actions": "Дії", - "theming": "Theming", - "localization": "Локалізація:", - "router": "Роутер:", + "theming": "Темізація", + "localization": "Локалізація", + "router": "Роутер", "useSonar": "Підключити Sonar?", + "firebaseAuth": "Інтегрувати Firebase з FirebaseAuth?", "integrateGraphQl": "Інтегрувати GraphQL?", + "integrateSentry": "Інтегрувати Sentry?", "useScreenUtil": "Використовувати Screen Util?", "generateSonarConfig": "Згенерувати конфіг Sonar?", "modifySigningVars": "Змінити дані підпису...", @@ -144,5 +146,8 @@ "parseErrorMessage": "Не вдалося отримати компоненти Swagger. Спробуйте знову або зв'яжіться з підтримкою, якщо не вдається оторимати компоненти.", "noDataComponents": "Компоненти не знайдено", "projectNameHelperText": "Назва проєкту має бути повністю маленькими літерами, з підкресленнями, щоб відокремити слова. Також переконайтеся, що назва є дійсним ідентифікатором Dart - вона не починається з цифр, не є зарезервованим словом, не починається і не закінчується символом підкреслення", - "organizationNameHelperText": "Цифра не може бути першим символом у сегменті пакету. У пакеті повинен бути хоча б один роздільник '.'. Кілька символів '.' підряд не допускаються." + "organizationNameHelperText": "Цифра не може бути першим символом у сегменті пакету. У пакеті повинен бути хоча б один роздільник '.'. Кілька символів '.' підряд не допускаються.", + "changeStateManagerError": "Попередження зміни стейт менеджера", + "changeStateManagerErrorContent": "Зміна стейт мененджера змінить ... на {variant}. Дійсно бажаєте продовжити?", + "screenClassNameHelperText": "Перший символ у назві класу має бути літерою" } \ No newline at end of file diff --git a/lib/core/router/app_router.dart b/lib/app/router/app_router.dart similarity index 99% rename from lib/core/router/app_router.dart rename to lib/app/router/app_router.dart index ae567229..9b985519 100644 --- a/lib/core/router/app_router.dart +++ b/lib/app/router/app_router.dart @@ -14,6 +14,7 @@ import 'package:onix_flutter_bricks/presentation/screen/summary_screen/summary_s import 'package:onix_flutter_bricks/presentation/screen/swagger_parser_screen/swagger_parser_screen.dart'; //{imports end} +// ignore_for_file: cast_nullable_to_non_nullable class AppRouter { static const _initialLocation = '/'; static const _splashScreen = '/'; diff --git a/lib/app/util/enum/swagger_path_request_type.dart b/lib/app/util/enum/swagger_path_request_type.dart index 382c04c6..bced5347 100644 --- a/lib/app/util/enum/swagger_path_request_type.dart +++ b/lib/app/util/enum/swagger_path_request_type.dart @@ -3,6 +3,7 @@ enum SwaggerPathRequestType { post, put, delete, + patch, update; static SwaggerPathRequestType fromString(String input) => diff --git a/lib/app/util/extenstion/dynamic_extension.dart b/lib/app/util/extenstion/dynamic_extension.dart index 00a93a87..c07b1c49 100644 --- a/lib/app/util/extenstion/dynamic_extension.dart +++ b/lib/app/util/extenstion/dynamic_extension.dart @@ -1,9 +1,13 @@ +import 'package:onix_flutter_bricks/app/util/extenstion/variable_name_extension.dart'; + extension DynamicExtension on Map { List asStringList(String key) { + if (this[key] == null) return []; return (this[key] as List).map((e) => e as String).toList(); } List> asObjectList(String key) { + if (this[key] == null) return []; return (this[key] as List) .map((e) => e as Map) .toList(); @@ -16,7 +20,7 @@ extension DynamicExtension on Map { final requestTags = (value as Map).asStringList('tags'); if (requestTags.isNotEmpty) { - final tagName = requestTags.first; + final tagName = requestTags.first.clearDataComponentsName(); if (!tags.contains(tagName)) { tags.add(tagName); diff --git a/lib/app/util/extenstion/swagger_reference_extension.dart b/lib/app/util/extenstion/swagger_reference_extension.dart index 9590bcde..e6ec058d 100644 --- a/lib/app/util/extenstion/swagger_reference_extension.dart +++ b/lib/app/util/extenstion/swagger_reference_extension.dart @@ -5,7 +5,7 @@ import 'package:recase/recase.dart'; extension SwaggerReferenceExtenson on SwaggerReference { String getReferenceMapperImport(String projectName) { final name = getTypeDeclaration(DataFileType.none).snakeCase; - return 'import \'package:$projectName/data/mapper/$name/${name}_mapper.dart\';'; + return "import 'package:$projectName/data/mapper/$name/${name}_mapper.dart';"; } String getReferenceMapperDeclaration({bool private = true}) { diff --git a/lib/app/util/extenstion/swagger_type_extension.dart b/lib/app/util/extenstion/swagger_type_extension.dart index 1b987277..0ff9588c 100644 --- a/lib/app/util/extenstion/swagger_type_extension.dart +++ b/lib/app/util/extenstion/swagger_type_extension.dart @@ -20,7 +20,7 @@ extension SwaggerTypeExtension on String { //['string', 'integer', 'boolean', 'number'] switch (this) { case 'string': - return '\'\''; + return "''"; case 'integer': return '-1'; case 'boolean': @@ -50,7 +50,7 @@ extension SwaggerTypeRefExtension on SwaggerType { return true; } else if (this is SwaggerArray) { final array = this as SwaggerArray; - return (array.itemType.type is SwaggerReference); + return array.itemType.type is SwaggerReference; } return false; } diff --git a/lib/app/util/extenstion/variable_name_extension.dart b/lib/app/util/extenstion/variable_name_extension.dart index cc276e85..0bbab5a3 100644 --- a/lib/app/util/extenstion/variable_name_extension.dart +++ b/lib/app/util/extenstion/variable_name_extension.dart @@ -3,7 +3,7 @@ import 'package:recase/recase.dart'; extension VariableNameExtension on String { String clearDataComponentsName() { - final cleanFromSpaces = pascalCase.replaceAll(RegExp(r"[^\s\w]"), ''); + final cleanFromSpaces = pascalCase.replaceAll(RegExp(r'[^\s\w]'), ''); if (cleanFromSpaces.contains(SwaggerConst.swaggerRequestKey)) { return cleanFromSpaces.replaceAll(SwaggerConst.swaggerRequestKey, ''); } @@ -12,11 +12,15 @@ extension VariableNameExtension on String { } if (cleanFromSpaces.contains(SwaggerConst.swaggerRequestTitleKey)) { return cleanFromSpaces.replaceAll( - SwaggerConst.swaggerRequestTitleKey, ''); + SwaggerConst.swaggerRequestTitleKey, + '', + ); } if (cleanFromSpaces.contains(SwaggerConst.swaggerResponseTitleKey)) { return cleanFromSpaces.replaceAll( - SwaggerConst.swaggerResponseTitleKey, ''); + SwaggerConst.swaggerResponseTitleKey, + '', + ); } if (cleanFromSpaces.contains(SwaggerConst.swaggerObjectDTO)) { @@ -26,7 +30,7 @@ extension VariableNameExtension on String { } String clearEnumComponentName() { - final cleanFromSpaces = pascalCase.replaceAll(RegExp(r"[^\s\w]"), ''); + final cleanFromSpaces = pascalCase.replaceAll(RegExp(r'[^\s\w]'), ''); if (cleanFromSpaces.contains(SwaggerConst.swaggerTypeKey)) { return cleanFromSpaces.replaceAll(SwaggerConst.swaggerTypeKey, ''); } @@ -38,7 +42,7 @@ extension VariableNameExtension on String { String clearPathToName() { final cleanFromSpaces = - replaceAll('/', ' ').replaceAll(RegExp(r"[^\s\w]"), '').snakeCase; + replaceAll('/', ' ').replaceAll(RegExp(r'[^\s\w]'), '').snakeCase; return cleanFromSpaces; } } diff --git a/lib/app/util/extenstion/variable_sort_extension.dart b/lib/app/util/extenstion/variable_sort_extension.dart index b34fac05..a39b7be2 100644 --- a/lib/app/util/extenstion/variable_sort_extension.dart +++ b/lib/app/util/extenstion/variable_sort_extension.dart @@ -4,16 +4,14 @@ extension VariiableSortExtenson on List { List sortByRequired() { final copy = List.from( this, - growable: true, - ); - copy.sort( - (a, b) { - if (b.isRequired) { - return 1; - } - return -1; - }, - ); + )..sort( + (a, b) { + if (b.isRequired) { + return 1; + } + return -1; + }, + ); return copy; } } diff --git a/lib/app/util/formatters/first_character_is_not_digit_formatter.dart b/lib/app/util/formatters/first_character_is_not_digit_formatter.dart new file mode 100644 index 00000000..d5cee2ae --- /dev/null +++ b/lib/app/util/formatters/first_character_is_not_digit_formatter.dart @@ -0,0 +1,17 @@ +import 'package:flutter/services.dart'; + +class FirstCharacterNotDigitFormatter extends TextInputFormatter { + const FirstCharacterNotDigitFormatter(); + + @override + TextEditingValue formatEditUpdate( + TextEditingValue oldValue, + TextEditingValue newValue, + ) { + if (newValue.text.isNotEmpty && + newValue.text[0].contains(RegExp('[0-9]'))) { + return oldValue; + } + return newValue; + } +} diff --git a/lib/core/arch/widget/common/misk.dart b/lib/app/widget/common/misk.dart similarity index 99% rename from lib/core/arch/widget/common/misk.dart rename to lib/app/widget/common/misk.dart index f6674c16..b4f7a782 100644 --- a/lib/core/arch/widget/common/misk.dart +++ b/lib/app/widget/common/misk.dart @@ -8,8 +8,8 @@ class Delimiter extends SizedBox { class ClickableWidget extends StatelessWidget { const ClickableWidget({ - super.key, required this.child, + super.key, this.onTap, this.color = Colors.transparent, this.splashColor, @@ -32,7 +32,7 @@ class ClickableWidget extends StatelessWidget { elevation: elevation, borderRadius: borderRadius ?? borderRadiusInk, child: InkWell( - borderRadius: borderRadiusInk ?? BorderRadius.circular(0.0), + borderRadius: borderRadiusInk ?? BorderRadius.circular(0), splashColor: splashColor ?? Theme.of(context).primaryColor.withOpacity(0.03), highlightColor: diff --git a/lib/core/arch/widget/common/toast.dart b/lib/app/widget/common/toast.dart similarity index 93% rename from lib/core/arch/widget/common/toast.dart rename to lib/app/widget/common/toast.dart index 164a3425..9724c947 100644 --- a/lib/core/arch/widget/common/toast.dart +++ b/lib/app/widget/common/toast.dart @@ -10,7 +10,7 @@ class CustomToast { timeInSecForIosWeb: 2, backgroundColor: Colors.red, textColor: Colors.white, - fontSize: 16.0, + fontSize: 16, ); } @@ -21,7 +21,7 @@ class CustomToast { gravity: ToastGravity.CENTER, backgroundColor: Colors.black54, timeInSecForIosWeb: 5, - fontSize: 16.0, + fontSize: 16, ); } } diff --git a/lib/core/arch/bloc/app_bloc_observer.dart b/lib/core/arch/bloc/app_bloc_observer.dart deleted file mode 100644 index 4b9c603f..00000000 --- a/lib/core/arch/bloc/app_bloc_observer.dart +++ /dev/null @@ -1,16 +0,0 @@ -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/di/app.dart'; - -class AppBlocObserver extends BlocObserver { - @override - void onEvent(Bloc bloc, Object? event) { - logger.d('$event'); - super.onEvent(bloc, event); - } - - @override - void onError(BlocBase bloc, Object error, StackTrace stackTrace) { - logger.d('$stackTrace'); - super.onError(bloc, error, stackTrace); - } -} diff --git a/lib/core/arch/bloc/base_bloc.dart b/lib/core/arch/bloc/base_bloc.dart deleted file mode 100644 index 248e2d7f..00000000 --- a/lib/core/arch/bloc/base_bloc.dart +++ /dev/null @@ -1,50 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/sr_mixin.dart'; -import 'package:onix_flutter_bricks/core/arch/domain/entity/failure/failure.dart'; - -abstract class BaseBloc extends Bloc - with SingleResultMixin { - @protected - late StreamController _errorStreamController; - @protected - late StreamController _progressStreamController; - - Stream get failureStream => _errorStreamController.stream; - Stream get progressStream => _progressStreamController.stream; - - BaseBloc(super.initialState) { - _errorStreamController = StreamController.broadcast(); - _progressStreamController = StreamController.broadcast(); - } - - void showProgress() { - if (!_progressStreamController.isClosed) { - _progressStreamController.add(true); - } - } - - Future hideProgress() async { - await Future.delayed(const Duration(milliseconds: 50)); - if (!_progressStreamController.isClosed) { - _progressStreamController.add(false); - } - } - - void onFailure(Failure failure) { - if (!_errorStreamController.isClosed) { - _errorStreamController.add(failure); - } - } - - void dispose() { - if (!_errorStreamController.isClosed) { - _errorStreamController.close(); - } - if (!_progressStreamController.isClosed) { - _progressStreamController.close(); - } - } -} diff --git a/lib/core/arch/bloc/base_block_state.dart b/lib/core/arch/bloc/base_block_state.dart deleted file mode 100644 index 58b6b69c..00000000 --- a/lib/core/arch/bloc/base_block_state.dart +++ /dev/null @@ -1,103 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:get_it/get_it.dart'; -import 'package:loader_overlay/loader_overlay.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/stream_listener.dart'; - -typedef ListenDelegate = void Function(BuildContext context, S state); -typedef StateListener = Widget Function(S state); -typedef SingleResultListener = void Function( - BuildContext context, - SR singleResult, -); - -abstract class BaseState, SR, - W extends StatefulWidget> extends State { - bool lazyBloc = false; - B? _bloc; - - @override - Widget build(BuildContext context) { - return BlocProvider( - create: (context) { - final bloc = createBloc(); - onBlocCreated(context, bloc); - _bloc = bloc; - return bloc; - }, - lazy: lazyBloc, - child: Builder( - builder: (context) { - initParams(context); - return buildWidget(context); - }, - ), - ); - } - - @override - void dispose() { - if (_bloc != null) { - _bloc?.dispose(); - } - super.dispose(); - } - - B blocOf(BuildContext context) => context.read(); - - B createBloc() => GetIt.I.get(); - - Widget srObserver({ - required BuildContext context, - required Widget child, - required SingleResultListener onSR, - }) { - return StreamListener( - stream: (_bloc ?? blocOf(context)).singleResults, - onData: (data) { - onSR(context, data); - }, - child: child, - ); - } - - Widget blocConsumer({ - required StateListener stateListener, - ListenDelegate? listenDelegate, - BlocBuilderCondition? buildWhen, - BlocListenerCondition? listenWhen, - }) { - return BlocConsumer( - builder: (_, state) => stateListener(state), - listener: listenDelegate ?? _defaultListenDelegate, - buildWhen: buildWhen, - listenWhen: listenWhen, - ); - } - - Widget blocBuilder({ - required BlocWidgetBuilder builder, - BlocBuilderCondition? buildWhen, - }) { - return BlocBuilder(builder: builder, buildWhen: buildWhen); - } - - void onBlocCreated(BuildContext context, B bloc) { - bloc.progressStream.listen((event) async { - if (event) { - context.loaderOverlay.show(); - } else { - context.loaderOverlay.hide(); - } - }); - } - - // ignore: no-empty-block - void initParams(BuildContext context) {} - - Widget buildWidget(BuildContext context); - - // ignore: no-empty-block - void _defaultListenDelegate(BuildContext context, S state) {} -} diff --git a/lib/core/arch/bloc/sr_mixin.dart b/lib/core/arch/bloc/sr_mixin.dart deleted file mode 100644 index a5c4b514..00000000 --- a/lib/core/arch/bloc/sr_mixin.dart +++ /dev/null @@ -1,49 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; - -/// Mixin for extending the block's capabilities to support SingleResult - events that need to be rendered 1 time -/// - Navigation -/// - Toast -/// - Snack -/// - Some interaction with the animation -mixin SingleResultMixin on Bloc - implements SingleResultProvider, SingleResultEmmiter { - @protected - final StreamController _srController = StreamController.broadcast(); - - @override - Stream get singleResults => _srController.stream; - - @override - void addSr(SR sr) { - final observer = Bloc.observer; - if (observer is SrBlocObserver) observer.onSr(this, sr); - if (!_srController.isClosed) _srController.add(sr); - } - - @override - Future close() { - _srController.close(); - - return super.close(); - } -} - -/// Protocol for providing a stream of events [SingleResult] -abstract class SingleResultProvider { - Stream get singleResults; -} - -/// Protocol for receiving events [SingleResult] -abstract class SingleResultEmmiter { - void addSr(SingleResult sr); -} - -/// Extending Observer to support logging SingleResult events -class SrBlocObserver extends BlocObserver { - @protected - @mustCallSuper - void onSr(Bloc bloc, SR sr) {} -} diff --git a/lib/core/arch/bloc/stream_listener.dart b/lib/core/arch/bloc/stream_listener.dart deleted file mode 100644 index 4628e71b..00000000 --- a/lib/core/arch/bloc/stream_listener.dart +++ /dev/null @@ -1,64 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/widgets.dart'; - -/// Widget for managing the Stream [stream] life cycle supplied to the widget tree. -class StreamListener extends StatefulWidget { - final Stream stream; - - final Widget child; - final void Function(T event) onData; - final Function? onError; - final Function()? onDone; - final bool? cancelOnError; - - const StreamListener({ - required this.stream, - required this.child, - required this.onData, - this.onError, - this.onDone, - this.cancelOnError, - super.key, - }); - - @override - State> createState() => _StreamListenerState(); -} - -class _StreamListenerState extends State> { - @override - void initState() { - super.initState(); - listen(); - } - - @override - void didUpdateWidget(covariant StreamListener oldWidget) { - super.didUpdateWidget(oldWidget); - _streamSubs?.cancel(); - listen(); - } - - @override - Widget build(BuildContext context) { - return widget.child; - } - - StreamSubscription? _streamSubs; - - @override - void dispose() { - _streamSubs?.cancel(); - super.dispose(); - } - - void listen() { - _streamSubs = widget.stream.listen( - widget.onData, - onDone: widget.onDone, - onError: widget.onError, - cancelOnError: widget.cancelOnError, - ); - } -} diff --git a/lib/core/arch/data/local/prefs/base_preferences.dart b/lib/core/arch/data/local/prefs/base_preferences.dart deleted file mode 100644 index b28f5a45..00000000 --- a/lib/core/arch/data/local/prefs/base_preferences.dart +++ /dev/null @@ -1,58 +0,0 @@ -import 'package:shared_preferences/shared_preferences.dart'; - -class BasePreferences { - Future get(String key, T defaultValue) async { - final prefs = await SharedPreferences.getInstance(); - T result; - - switch (defaultValue.runtimeType) { - case const (String): - final value = prefs.getString(key) as T?; - result = value ?? defaultValue; - break; - case const (bool): - final value = prefs.getBool(key) as T?; - result = value ?? defaultValue; - break; - case const (double): - final value = prefs.getDouble(key) as T?; - result = value ?? defaultValue; - break; - case const (int): - final value = prefs.getInt(key) as T?; - result = value ?? defaultValue; - break; - default: - return defaultValue; - } - return result; - } - - Future put(String key, T value) async { - final prefs = await SharedPreferences.getInstance(); - switch (value.runtimeType) { - case const (String): - await prefs.setString(key, value as String); - break; - case const (bool): - await prefs.setBool(key, value as bool); - break; - case const (double): - await prefs.setDouble(key, value as double); - break; - case const (int): - await prefs.setInt(key, value as int); - break; - } - } - - Future clearPrefs() async { - final prefs = await SharedPreferences.getInstance(); - await prefs.clear(); - } - - Future removePrefByKey(String key) async { - final prefs = await SharedPreferences.getInstance(); - return prefs.remove(key); - } -} diff --git a/lib/core/arch/domain/common/converter/mapper.dart b/lib/core/arch/domain/common/converter/mapper.dart deleted file mode 100644 index b1c83107..00000000 --- a/lib/core/arch/domain/common/converter/mapper.dart +++ /dev/null @@ -1,10 +0,0 @@ -//ignore: one_member_abstracts -abstract class Mapper { - E map(T from); -} - -abstract class MapperIterable extends Mapper { - Iterable mapIterable(Iterable from) { - return from.map(map); - } -} diff --git a/lib/core/arch/domain/entity/failure/api_failure.dart b/lib/core/arch/domain/entity/failure/api_failure.dart deleted file mode 100644 index 1b16d973..00000000 --- a/lib/core/arch/domain/entity/failure/api_failure.dart +++ /dev/null @@ -1,12 +0,0 @@ -import 'package:onix_flutter_bricks/core/arch/domain/entity/failure/failure.dart'; - -class ApiFailure implements Failure { - final int code; - - ApiFailure({required this.code}); -} - -///When Failed to parse swagger components -class SwaggerParserFailure implements Failure { - SwaggerParserFailure(); -} diff --git a/lib/core/arch/domain/entity/failure/failure.dart b/lib/core/arch/domain/entity/failure/failure.dart deleted file mode 100644 index 1eeb5e14..00000000 --- a/lib/core/arch/domain/entity/failure/failure.dart +++ /dev/null @@ -1 +0,0 @@ -abstract class Failure {} diff --git a/lib/core/arch/domain/entity/result/result.dart b/lib/core/arch/domain/entity/result/result.dart deleted file mode 100644 index 7e814a2c..00000000 --- a/lib/core/arch/domain/entity/result/result.dart +++ /dev/null @@ -1,25 +0,0 @@ -import 'package:freezed_annotation/freezed_annotation.dart'; -import 'package:onix_flutter_bricks/core/arch/domain/entity/failure/failure.dart'; - -part 'result.freezed.dart'; - -@freezed -class Result with _$Result { - bool get success => this is _ResultSuccess; - - bool get isError => this is ResultError; - - ///WARNING. ALWAYS CHECK success == true before call - T get data => (this as _ResultSuccess).data; - - ///WARNING. ALWAYS CHECK isError == true before call - ResultError get error => this as ResultError; - - const Result._(); - - const factory Result.success(T data) = _ResultSuccess; - - const factory Result.error({ - required Failure failure, - }) = ResultError; -} diff --git a/lib/core/arch/domain/entity/result/result.freezed.dart b/lib/core/arch/domain/entity/result/result.freezed.dart deleted file mode 100644 index 36ce48cd..00000000 --- a/lib/core/arch/domain/entity/result/result.freezed.dart +++ /dev/null @@ -1,346 +0,0 @@ -// coverage:ignore-file -// GENERATED CODE - DO NOT MODIFY BY HAND -// ignore_for_file: type=lint -// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark - -part of 'result.dart'; - -// ************************************************************************** -// FreezedGenerator -// ************************************************************************** - -T _$identity(T value) => value; - -final _privateConstructorUsedError = UnsupportedError( - 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); - -/// @nodoc -mixin _$Result { - @optionalTypeArgs - TResult when({ - required TResult Function(T data) success, - required TResult Function(Failure failure) error, - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function(T data)? success, - TResult? Function(Failure failure)? error, - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult maybeWhen({ - TResult Function(T data)? success, - TResult Function(Failure failure)? error, - required TResult orElse(), - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult map({ - required TResult Function(_ResultSuccess value) success, - required TResult Function(ResultError value) error, - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(_ResultSuccess value)? success, - TResult? Function(ResultError value)? error, - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult maybeMap({ - TResult Function(_ResultSuccess value)? success, - TResult Function(ResultError value)? error, - required TResult orElse(), - }) => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $ResultCopyWith { - factory $ResultCopyWith(Result value, $Res Function(Result) then) = - _$ResultCopyWithImpl>; -} - -/// @nodoc -class _$ResultCopyWithImpl> - implements $ResultCopyWith { - _$ResultCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; -} - -/// @nodoc -abstract class _$$ResultSuccessImplCopyWith { - factory _$$ResultSuccessImplCopyWith(_$ResultSuccessImpl value, - $Res Function(_$ResultSuccessImpl) then) = - __$$ResultSuccessImplCopyWithImpl; - @useResult - $Res call({T data}); -} - -/// @nodoc -class __$$ResultSuccessImplCopyWithImpl - extends _$ResultCopyWithImpl> - implements _$$ResultSuccessImplCopyWith { - __$$ResultSuccessImplCopyWithImpl(_$ResultSuccessImpl _value, - $Res Function(_$ResultSuccessImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? data = freezed, - }) { - return _then(_$ResultSuccessImpl( - freezed == data - ? _value.data - : data // ignore: cast_nullable_to_non_nullable - as T, - )); - } -} - -/// @nodoc - -class _$ResultSuccessImpl extends _ResultSuccess { - const _$ResultSuccessImpl(this.data) : super._(); - - @override - final T data; - - @override - String toString() { - return 'Result<$T>.success(data: $data)'; - } - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$ResultSuccessImpl && - const DeepCollectionEquality().equals(other.data, data)); - } - - @override - int get hashCode => - Object.hash(runtimeType, const DeepCollectionEquality().hash(data)); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$ResultSuccessImplCopyWith> get copyWith => - __$$ResultSuccessImplCopyWithImpl>( - this, _$identity); - - @override - @optionalTypeArgs - TResult when({ - required TResult Function(T data) success, - required TResult Function(Failure failure) error, - }) { - return success(data); - } - - @override - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function(T data)? success, - TResult? Function(Failure failure)? error, - }) { - return success?.call(data); - } - - @override - @optionalTypeArgs - TResult maybeWhen({ - TResult Function(T data)? success, - TResult Function(Failure failure)? error, - required TResult orElse(), - }) { - if (success != null) { - return success(data); - } - return orElse(); - } - - @override - @optionalTypeArgs - TResult map({ - required TResult Function(_ResultSuccess value) success, - required TResult Function(ResultError value) error, - }) { - return success(this); - } - - @override - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(_ResultSuccess value)? success, - TResult? Function(ResultError value)? error, - }) { - return success?.call(this); - } - - @override - @optionalTypeArgs - TResult maybeMap({ - TResult Function(_ResultSuccess value)? success, - TResult Function(ResultError value)? error, - required TResult orElse(), - }) { - if (success != null) { - return success(this); - } - return orElse(); - } -} - -abstract class _ResultSuccess extends Result { - const factory _ResultSuccess(final T data) = _$ResultSuccessImpl; - const _ResultSuccess._() : super._(); - - T get data; - @JsonKey(ignore: true) - _$$ResultSuccessImplCopyWith> get copyWith => - throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class _$$ResultErrorImplCopyWith { - factory _$$ResultErrorImplCopyWith(_$ResultErrorImpl value, - $Res Function(_$ResultErrorImpl) then) = - __$$ResultErrorImplCopyWithImpl; - @useResult - $Res call({Failure failure}); -} - -/// @nodoc -class __$$ResultErrorImplCopyWithImpl - extends _$ResultCopyWithImpl> - implements _$$ResultErrorImplCopyWith { - __$$ResultErrorImplCopyWithImpl( - _$ResultErrorImpl _value, $Res Function(_$ResultErrorImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? failure = null, - }) { - return _then(_$ResultErrorImpl( - failure: null == failure - ? _value.failure - : failure // ignore: cast_nullable_to_non_nullable - as Failure, - )); - } -} - -/// @nodoc - -class _$ResultErrorImpl extends ResultError { - const _$ResultErrorImpl({required this.failure}) : super._(); - - @override - final Failure failure; - - @override - String toString() { - return 'Result<$T>.error(failure: $failure)'; - } - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$ResultErrorImpl && - (identical(other.failure, failure) || other.failure == failure)); - } - - @override - int get hashCode => Object.hash(runtimeType, failure); - - @JsonKey(ignore: true) - @override - @pragma('vm:prefer-inline') - _$$ResultErrorImplCopyWith> get copyWith => - __$$ResultErrorImplCopyWithImpl>( - this, _$identity); - - @override - @optionalTypeArgs - TResult when({ - required TResult Function(T data) success, - required TResult Function(Failure failure) error, - }) { - return error(failure); - } - - @override - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function(T data)? success, - TResult? Function(Failure failure)? error, - }) { - return error?.call(failure); - } - - @override - @optionalTypeArgs - TResult maybeWhen({ - TResult Function(T data)? success, - TResult Function(Failure failure)? error, - required TResult orElse(), - }) { - if (error != null) { - return error(failure); - } - return orElse(); - } - - @override - @optionalTypeArgs - TResult map({ - required TResult Function(_ResultSuccess value) success, - required TResult Function(ResultError value) error, - }) { - return error(this); - } - - @override - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(_ResultSuccess value)? success, - TResult? Function(ResultError value)? error, - }) { - return error?.call(this); - } - - @override - @optionalTypeArgs - TResult maybeMap({ - TResult Function(_ResultSuccess value)? success, - TResult Function(ResultError value)? error, - required TResult orElse(), - }) { - if (error != null) { - return error(this); - } - return orElse(); - } -} - -abstract class ResultError extends Result { - const factory ResultError({required final Failure failure}) = - _$ResultErrorImpl; - const ResultError._() : super._(); - - Failure get failure; - @JsonKey(ignore: true) - _$$ResultErrorImplCopyWith> get copyWith => - throw _privateConstructorUsedError; -} diff --git a/lib/core/arch/widget/common/ensure_visible.dart.dart b/lib/core/arch/widget/common/ensure_visible.dart.dart deleted file mode 100644 index 31efc6ec..00000000 --- a/lib/core/arch/widget/common/ensure_visible.dart.dart +++ /dev/null @@ -1,169 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; - -/// -/// Helper class that ensures a Widget is visible when it has the focus -/// For example, for a TextFormField when the keyboard is displayed -/// -/// How to use it: -/// -/// In the class that implements the Form, -/// Instantiate a FocusNode -/// FocusNode _focusNode = new FocusNode(); -/// -/// In the build(BuildContext context), wrap the TextFormField as follows: -/// -/// new EnsureVisibleWhenFocused( -/// focusNode: _focusNode, -/// child: new TextFormField( -/// ... -/// focusNode: _focusNode, -/// ), -/// ), -/// -/// Initial source code written by Collin Jackson. -/// Extended (see highlighting) to cover the case when the keyboard is dismissed and the -/// user clicks the TextFormField/TextField which still has the focus. -/// -class EnsureVisibleWhenFocused extends StatefulWidget { - /// The node we will monitor to determine if the child is focused - final FocusNode focusNode; - - /// The child widget that we are wrapping - final Widget child; - - /// The curve we will use to scroll ourselves into view. - /// - /// Defaults to Curves.ease. - final Curve curve; - - /// The duration we will use to scroll ourselves into view - /// - /// Defaults to 100 milliseconds. - final Duration duration; - - /// The alignment will override the default alignment behaviour - /// - /// No default value. - final double? alignment; - - const EnsureVisibleWhenFocused({ - required this.child, - required this.focusNode, - super.key, - this.curve = Curves.easeIn, - this.duration = const Duration(milliseconds: 100), - this.alignment, - }); - - @override - // ignore: library_private_types_in_public_api - _EnsureVisibleWhenFocusedState createState() => - _EnsureVisibleWhenFocusedState(); -} - -/// -/// We implement the WidgetsBindingObserver to be notified of any change to the window metrics -/// -class _EnsureVisibleWhenFocusedState extends State - with WidgetsBindingObserver { - @override - void initState() { - super.initState(); - widget.focusNode.addListener(_ensureVisible); - WidgetsBinding.instance.addObserver(this); - } - - /// - /// This routine is invoked when the window metrics have changed. - /// This happens when the keyboard is open or dismissed, among others. - /// It is the opportunity to check if the field has the focus - /// and to ensure it is fully visible in the viewport when - /// the keyboard is displayed - /// - @override - void didChangeMetrics() { - if (widget.focusNode.hasFocus) { - _ensureVisible(); - } - } - - @override - Widget build(BuildContext context) => widget.child; - - @override - void dispose() { - WidgetsBinding.instance.removeObserver(this); - widget.focusNode.removeListener(_ensureVisible); - super.dispose(); - } - - /// - /// This routine waits for the keyboard to come into view. - /// In order to prevent some issues if the Widget is dismissed in the - /// middle of the loop, we need to check the "mounted" property - /// - /// This method was suggested by Peter Yuen (see discussion). - /// - Future _keyboardToggled() async { - if (mounted) { - final edgeInsets = MediaQuery.of(context).viewInsets; - while (mounted && MediaQuery.of(context).viewInsets == edgeInsets) { - await Future.delayed(const Duration(milliseconds: 10)); - } - } - - return; - } - - Future _ensureVisible() async { - // Wait for the keyboard to come into view - await Future.any([ - Future.delayed(const Duration(milliseconds: 300)), - _keyboardToggled(), - ]); - - // No need to go any further if the node has not the focus - if (!widget.focusNode.hasFocus) { - return; - } - - // Find the object which has the focus - if (!mounted) { - return; - } - // ignore: avoid-non-null-assertion - final object = context.findRenderObject()!; - final viewport = RenderAbstractViewport.of(object); - - // Get the Scrollable state (in order to retrieve its offset) - // ignore: avoid-non-null-assertion - final scrollableState = Scrollable.of(context); - - // Get its offset - final position = scrollableState.position; - late double alignment; - - if (position.pixels > viewport.getOffsetToReveal(object, 0.0).offset) { - // Move down to the top of the viewport - alignment = 0.0; - } else if (position.pixels < - viewport.getOffsetToReveal(object, 1.0).offset) { - // Move up to the bottom of the viewport - alignment = 1.0; - } else { - // No scrolling is necessary to reveal the child - return; - } - - //ignore: unawaited_futures - position.ensureVisible( - object, - alignment: widget.alignment ?? alignment, - duration: widget.duration, - curve: widget.curve, - ); - } -} diff --git a/lib/core/arch/widget/common/keyboard_closable.dart b/lib/core/arch/widget/common/keyboard_closable.dart deleted file mode 100644 index ea49bc49..00000000 --- a/lib/core/arch/widget/common/keyboard_closable.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'package:flutter/material.dart'; - -class KeyboardClosable extends StatelessWidget { - const KeyboardClosable({ - super.key, - required this.child, - }); - - final Widget child; - - @override - Widget build(BuildContext context) => GestureDetector( - behavior: HitTestBehavior.translucent, - onTap: () => FocusScope.of(context).unfocus(), - child: child, - ); -} diff --git a/lib/core/arch/widget/common/scroll_root_max.dart b/lib/core/arch/widget/common/scroll_root_max.dart deleted file mode 100644 index 02d17066..00000000 --- a/lib/core/arch/widget/common/scroll_root_max.dart +++ /dev/null @@ -1,30 +0,0 @@ -import 'package:flutter/material.dart'; - -class ScrollRootMax extends StatelessWidget { - const ScrollRootMax({ - super.key, - required this.child, - }); - - final Widget child; - - @override - Widget build(BuildContext context) { - return LayoutBuilder( - builder: (BuildContext context, BoxConstraints viewportConstraints) { - return SingleChildScrollView( - physics: const BouncingScrollPhysics(), - child: ConstrainedBox( - constraints: BoxConstraints( - minHeight: viewportConstraints.maxHeight, - minWidth: viewportConstraints.maxWidth, - ), - child: IntrinsicHeight( - child: child, - ), - ), - ); - }, - ); - } -} diff --git a/lib/core/arch/widget/common/scroll_root_min.dart b/lib/core/arch/widget/common/scroll_root_min.dart deleted file mode 100644 index ca7149d5..00000000 --- a/lib/core/arch/widget/common/scroll_root_min.dart +++ /dev/null @@ -1,29 +0,0 @@ -import 'package:flutter/material.dart'; - -class ScrollRootMin extends StatelessWidget { - const ScrollRootMin({ - super.key, - required this.child, - this.physics, - }); - - final Widget child; - final ScrollPhysics? physics; - - @override - Widget build(BuildContext context) { - return LayoutBuilder( - builder: (BuildContext context, BoxConstraints viewportConstraints) { - return SingleChildScrollView( - physics: physics ?? const BouncingScrollPhysics(), - child: ConstrainedBox( - constraints: BoxConstraints( - minHeight: viewportConstraints.maxHeight, - ), - child: child, - ), - ); - }, - ); - } -} diff --git a/lib/core/di/bloc.dart b/lib/core/di/bloc.dart index 5830884a..1abb9b32 100644 --- a/lib/core/di/bloc.dart +++ b/lib/core/di/bloc.dart @@ -1,4 +1,5 @@ import 'package:get_it/get_it.dart'; +import 'package:onix_flutter_bricks/domain/repository/screen_repository.dart'; import 'package:onix_flutter_bricks/domain/usecase/docs_generation/generate_documentation_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/fastlane/generate_fastlane_files_use_case.dart'; import 'package:onix_flutter_bricks/domain/usecase/file_generation/generate_screens_usecase.dart'; @@ -10,9 +11,11 @@ import 'package:onix_flutter_bricks/domain/usecase/process/get_branches_process_ import 'package:onix_flutter_bricks/domain/usecase/process/get_signing_fingerprint_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/process/run_osascript_process_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/process/run_process_usecase.dart'; +import 'package:onix_flutter_bricks/domain/usecase/screen/clear_screens_use_case.dart'; import 'package:onix_flutter_bricks/domain/usecase/styles/generate_styles_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/styles/get_figma_styles_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/swagger/create_swagger_components_usecase.dart'; +import 'package:onix_flutter_bricks/domain/usecase/swagger/empty_swagger_components_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/swagger/fetch_swagger_data_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/swagger/get_swagger_components_usecase.dart'; import 'package:onix_flutter_bricks/presentation/screen/data_components_screen_v2/bloc/data_components_screen_v2_bloc_imports.dart'; @@ -49,6 +52,7 @@ void registerBloc(GetIt getIt) { ..registerFactory( () => SwaggerParserScreenBloc( GetIt.I.get(), + GetIt.I.get(), ), ) ..registerFactory(ScreensScreenBloc.new) @@ -62,7 +66,11 @@ void registerBloc(GetIt getIt) { GetIt.I.get(), ), ) - ..registerFactory(ProjectSettingsScreenBloc.new) + ..registerFactory( + () => ProjectSettingsScreenBloc( + screenRepository: GetIt.I.get(), + ), + ) ..registerFactory(PlatformsScreenBloc.new) ..registerFactory( () => ProjectNameScreenBloc( @@ -74,6 +82,8 @@ void registerBloc(GetIt getIt) { () => ProcedureSelectionScreenBloc( GetIt.I.get(), GetIt.I.get(), + GetIt.I.get(), + GetIt.I.get(), ), ) ..registerFactory( diff --git a/lib/core/di/local.dart b/lib/core/di/local.dart index fc23e55d..eb956efe 100644 --- a/lib/core/di/local.dart +++ b/lib/core/di/local.dart @@ -1,5 +1,5 @@ import 'package:get_it/get_it.dart'; -import 'package:onix_flutter_bricks/core/arch/data/local/prefs/base_preferences.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; void registerLocal(GetIt getIt) { getIt.registerLazySingleton( diff --git a/lib/core/di/services.dart b/lib/core/di/services.dart index 35a712a9..90389de0 100644 --- a/lib/core/di/services.dart +++ b/lib/core/di/services.dart @@ -24,6 +24,7 @@ void registerAppServices(GetIt getIt) { ) ..registerLazySingleton(() => const FastlaneService()) ..registerLazySingleton( - () => ComponentGeneratorService()) - ..registerLazySingleton(() => GitCliffService()); + () => const ComponentGeneratorService(), + ) + ..registerLazySingleton(() => const GitCliffService()); } diff --git a/lib/core/di/source.dart b/lib/core/di/source.dart index b5a42a69..b614d2a6 100644 --- a/lib/core/di/source.dart +++ b/lib/core/di/source.dart @@ -15,7 +15,7 @@ void registerSources(GetIt getIt) { () => const FigmaRemoteDataSourceImpl(), ) ..registerLazySingleton( - () => SwaggerRemoteSourceImpl(), + () => const SwaggerRemoteSourceImpl(), ); //{sources end} } diff --git a/lib/core/di/usecase.dart b/lib/core/di/usecase.dart index 737072f8..224a6bb3 100644 --- a/lib/core/di/usecase.dart +++ b/lib/core/di/usecase.dart @@ -19,89 +19,100 @@ import 'package:onix_flutter_bricks/domain/usecase/process/get_branches_process_ import 'package:onix_flutter_bricks/domain/usecase/process/get_signing_fingerprint_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/process/run_osascript_process_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/process/run_process_usecase.dart'; +import 'package:onix_flutter_bricks/domain/usecase/screen/clear_screens_use_case.dart'; import 'package:onix_flutter_bricks/domain/usecase/styles/generate_styles_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/styles/get_figma_styles_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/swagger/create_swagger_components_usecase.dart'; +import 'package:onix_flutter_bricks/domain/usecase/swagger/empty_swagger_components_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/swagger/fetch_swagger_data_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/swagger/get_swagger_components_usecase.dart'; void registerUseCases(GetIt getIt) { getIt - ..registerLazySingleton( + ..registerFactory( () => AddOutputMessageUseCase( GetIt.I.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => GenerateDocumentationUseCase( GetIt.I.get(), GetIt.I.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => GenerateScreensUseCase( GetIt.I.get(), - GetIt.I.get(), GetIt.I.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => RunProcessUseCase(GetIt.I.get()), ) - ..registerLazySingleton( + ..registerFactory( () => RunOsaScriptProcessUseCase( GetIt.I.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => const GetBranchesProcessUseCase(), ) - ..registerLazySingleton( + ..registerFactory( () => GetFigmaStylesUseCase( GetIt.I.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => GenerateSigningConfigUseCase( GetIt.I.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => GenerateStylesUseCase( GetIt.I.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => GetGenerationOutputStream( GetIt.I.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => GenerateFastlaneFilesUseCase( outputService: getIt.get(), fastlaneService: getIt.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => const GetSigningFingerprintUseCase(), ) - ..registerLazySingleton( + ..registerFactory( () => FetchSwaggerDataUseCase( getIt.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => CreateSwaggerComponentsUseCase( getIt.get(), getIt.get(), ), ) - ..registerLazySingleton( + ..registerFactory( () => GetSwaggerComponentsUseCase( getIt.get(), ), ) - ..registerLazySingleton( + ..registerFactory( + () => ClearSwaggerComponentsUseCase( + getIt.get(), + ), + ) + ..registerFactory( + () => ClearScreensUseCase( + getIt.get(), + ), + ) + ..registerFactory( () => GenerateGitCliffFilesUseCase( outputService: getIt.get(), service: getIt.get(), diff --git a/lib/data/mapper/figma/figma_nodes_mapper.dart b/lib/data/mapper/figma/figma_nodes_mapper.dart index c40332ec..1db13aef 100644 --- a/lib/data/mapper/figma/figma_nodes_mapper.dart +++ b/lib/data/mapper/figma/figma_nodes_mapper.dart @@ -1,4 +1,3 @@ -import 'package:onix_flutter_bricks/core/arch/domain/common/converter/mapper.dart'; import 'package:onix_flutter_bricks/data/mapper/figma/properties_mapper.dart'; import 'package:onix_flutter_bricks/data/model/figma/nodes/connector/connector_node_data_model.dart'; import 'package:onix_flutter_bricks/data/model/figma/nodes/document/document_node_data_model.dart'; @@ -24,10 +23,11 @@ import 'package:onix_flutter_bricks/domain/entity/figma/nodes/table_cell_node/ta import 'package:onix_flutter_bricks/domain/entity/figma/nodes/text_node/text_node_entity.dart'; import 'package:onix_flutter_bricks/domain/entity/figma/nodes/vector_node/vector_node_entity.dart'; import 'package:onix_flutter_bricks/domain/entity/figma/properties/paint_property/paint_property.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; class FigmaNodesMapper { List mapNodesDataModelToEntity(List from) => - _MapNodeDataModelToEntity().mapIterable(from).toList(); + _MapNodeDataModelToEntity().mapList(from).toList(); } class _MapNodeDataModelToEntity diff --git a/lib/data/mapper/figma/properties_mapper.dart b/lib/data/mapper/figma/properties_mapper.dart index b0f47e95..bb4efbc3 100644 --- a/lib/data/mapper/figma/properties_mapper.dart +++ b/lib/data/mapper/figma/properties_mapper.dart @@ -1,4 +1,3 @@ -import 'package:onix_flutter_bricks/core/arch/domain/common/converter/mapper.dart'; import 'package:onix_flutter_bricks/data/model/figma/properties/node_style/figma_node_style.dart'; import 'package:onix_flutter_bricks/data/model/figma/properties/paint/paint_property_data_model.dart'; import 'package:onix_flutter_bricks/data/model/figma/properties/type_style/figma_type_style.dart'; @@ -6,12 +5,13 @@ import 'package:onix_flutter_bricks/domain/entity/figma/properties/color_propert import 'package:onix_flutter_bricks/domain/entity/figma/properties/node_style_property/node_style_property.dart'; import 'package:onix_flutter_bricks/domain/entity/figma/properties/paint_property/paint_property.dart'; import 'package:onix_flutter_bricks/domain/entity/figma/properties/type_style/type_style_metadata.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; class PropertyMapper { Iterable mapPaintPropertyDataModelToEntity( Iterable from, ) => - _MapPaintsPropertyDataModelToEntity().mapIterable(from); + _MapPaintsPropertyDataModelToEntity().mapList(from); NodeStyleProperty mapNodeStyleDataModelToEntity(FigmaNodeStyle from) => _MapNodeStyleDataModelToEntity().map(from); diff --git a/lib/data/mapper/swagger/swagger_mapper.dart b/lib/data/mapper/swagger/swagger_mapper.dart index 3aa459b9..4f4415af 100644 --- a/lib/data/mapper/swagger/swagger_mapper.dart +++ b/lib/data/mapper/swagger/swagger_mapper.dart @@ -15,7 +15,7 @@ import 'package:onix_flutter_bricks/domain/entity/component/source_component.dar class SwaggerMapper { List mapDataObjects(SwaggerResponse input) { final dataObjects = List.empty(growable: true); - for (var e in input.swaggerModels) { + for (final e in input.swaggerModels) { final variables = e.variables .map( (variable) => DataVariableComponent( @@ -38,8 +38,8 @@ class SwaggerMapper { List mapEnums(SwaggerResponse input) { final enumList = List.empty(growable: true); - for (var model in input.swaggerModels) { - for (var e in model.variables) { + for (final model in input.swaggerModels) { + for (final e in model.variables) { final enumClass = e.type.getSwaggerEnumReference(); if (enumClass != null) { enumList.add( @@ -56,12 +56,9 @@ class SwaggerMapper { List mapSources(SwaggerResponse input) { final sources = List.empty(growable: true); - for (var tag in input.swaggerTags) { - final sourceRequests = input.swaggerPaths - .where( - (e) => e.primaryTag == tag.name, - ) - .toList(); + for (final tag in input.swaggerTags) { + final sourceRequests = + input.swaggerPaths.where((e) => e.primaryTag == tag.name).toList(); final requests = _mapRequests(sourceRequests); sources.add( SourceComponent( @@ -75,7 +72,7 @@ class SwaggerMapper { List _mapRequests(List input) { final requests = List.empty(growable: true); - for (var path in input) { + for (final path in input) { final requestResponseParam = _mapResponseParams(path); final requestBody = _mapRequestBodyParams(path); final multipartParams = _mapRequestMultipartParams(path); @@ -94,6 +91,7 @@ class SwaggerMapper { ); requests.add(request); } + return requests; } @@ -124,12 +122,13 @@ class SwaggerMapper { final multipartParams = input.input.whereType(); final paramComponents = List.empty(growable: true); - for (var e in multipartParams) { + for (final e in multipartParams) { paramComponents.add( RequestMultipartComponent( - name: e.variable.name, - type: e.variable.type, - isRequired: e.variable.isRequired), + name: e.variable.name, + type: e.variable.type, + isRequired: e.variable.isRequired, + ), ); } return paramComponents; @@ -140,12 +139,13 @@ class SwaggerMapper { ) { final queryParams = input.input.whereType(); final paramComponents = List.empty(growable: true); - for (var e in queryParams) { + for (final e in queryParams) { paramComponents.add( RequestQueryComponent( - name: e.variable.name, - type: e.variable.type, - isRequired: e.variable.isRequired), + name: e.variable.name, + type: e.variable.type, + isRequired: e.variable.isRequired, + ), ); } return paramComponents; @@ -156,12 +156,13 @@ class SwaggerMapper { ) { final pathParams = input.input.whereType(); final paramComponents = List.empty(growable: true); - for (var e in pathParams) { + for (final e in pathParams) { paramComponents.add( RequestPathComponent( - name: e.variable.name, - type: e.variable.type, - isRequired: e.variable.isRequired), + name: e.variable.name, + type: e.variable.type, + isRequired: e.variable.isRequired, + ), ); } return paramComponents; diff --git a/lib/data/model/swagger/model/swagger_model_response_v2.dart b/lib/data/model/swagger/model/swagger_model_response_v2.dart index 027c0bda..a9e4c5db 100644 --- a/lib/data/model/swagger/model/swagger_model_response_v2.dart +++ b/lib/data/model/swagger/model/swagger_model_response_v2.dart @@ -15,7 +15,7 @@ class SwaggerModelResponseV2 extends BaseSwaggerModelResponse { String rawModelName, Map json, ) { - var modelName = rawModelName.clearDataComponentsName(); + final modelName = rawModelName.clearDataComponentsName(); var variables = List.empty(growable: true); diff --git a/lib/data/model/swagger/model/swagger_model_response_v3.dart b/lib/data/model/swagger/model/swagger_model_response_v3.dart index 81048b26..843d0aff 100644 --- a/lib/data/model/swagger/model/swagger_model_response_v3.dart +++ b/lib/data/model/swagger/model/swagger_model_response_v3.dart @@ -17,18 +17,18 @@ class SwaggerModelResponseV3 extends BaseSwaggerModelResponse { Map json, Map allObjects, ) { - List crossReferences = []; + var crossReferences = []; if (json.containsKey('allOf')) { - final allOff = (json).asObjectList('allOf'); + final allOff = json.asObjectList('allOf'); crossReferences = _getCrossReferences( allOff, allObjects, ); } - var modelName = rawModelName.clearDataComponentsName(); + final modelName = rawModelName.clearDataComponentsName(); - var variables = + final variables = List.empty(growable: true); final type = json['type']; final requiredVariables = (json.containsKey('required')) diff --git a/lib/data/model/swagger/model_variable/base_swagger_model_variable_response.dart b/lib/data/model/swagger/model_variable/base_swagger_model_variable_response.dart index 35bb7093..6adc7214 100644 --- a/lib/data/model/swagger/model_variable/base_swagger_model_variable_response.dart +++ b/lib/data/model/swagger/model_variable/base_swagger_model_variable_response.dart @@ -29,10 +29,18 @@ abstract class BaseSwaggerModelVariableResponse { switch (swaggerVersion) { case SwaggerVersionType.swagger2: return SwaggerModelVariableResponseV2.fromJson( - name, requiredVariables, json, from); + name, + requiredVariables, + json, + from, + ); case SwaggerVersionType.swagger3: return SwaggerModelVariableResponseV3.fromJson( - name, requiredVariables, json, from); + name, + requiredVariables, + json, + from, + ); case SwaggerVersionType.unsupported: return SwaggerModelVariableResponseUnsupported.unsupported(); } @@ -48,7 +56,7 @@ abstract class BaseSwaggerModelVariableResponse { @override String toString() { final typeSuffix = isRequired ? '' : '?'; - return '${type.toString()}$typeSuffix $name'; + return '$type$typeSuffix $name'; } @protected diff --git a/lib/data/model/swagger/model_variable/swagger_model_variable_response_v3.dart b/lib/data/model/swagger/model_variable/swagger_model_variable_response_v3.dart index e4693b3c..c59a53bb 100644 --- a/lib/data/model/swagger/model_variable/swagger_model_variable_response_v3.dart +++ b/lib/data/model/swagger/model_variable/swagger_model_variable_response_v3.dart @@ -25,6 +25,7 @@ class SwaggerModelVariableResponseV3 extends BaseSwaggerModelVariableResponse { requiredVariables, json, ); + if (rootType != null) { return SwaggerModelVariableResponseV3( name: name, @@ -123,6 +124,15 @@ class SwaggerModelVariableResponseV3 extends BaseSwaggerModelVariableResponse { typeValue, from: from, ); + } else if (json.containsKey('anyOf')) { + final anyOf = json.asObjectList('anyOf'); + if (anyOf.isEmpty) return null; + return BaseSwaggerModelVariableResponse.parseSimpleType( + name, + from, + requiredVariables, + anyOf.first, + ); } return null; } diff --git a/lib/data/model/swagger/path/swagger_path_response_v3.dart b/lib/data/model/swagger/path/swagger_path_response_v3.dart index 55b7620d..53c5a518 100644 --- a/lib/data/model/swagger/path/swagger_path_response_v3.dart +++ b/lib/data/model/swagger/path/swagger_path_response_v3.dart @@ -31,13 +31,14 @@ class SwaggerPathResponseV3 extends BaseSwaggerPathResponse { var description = ''; var operationId = ''; - //get primary tag + // get primary tag if (json.containsKey('tags')) { final tags = json.asStringList('tags'); - tag = - (tags.isNotEmpty) ? tags.first.clearDataComponentsName() : 'unnamed'; + tag = (tags.isNotEmpty) + ? tags.first.clearDataComponentsName() + : 'unnamed'; } - //get summary - description + // get summary - description if (json.containsKey('description')) { final descriptionRaw = json['description'] as String; description = descriptionRaw.split('\n').join('///\n'); diff --git a/lib/data/model/swagger/types/swagger_request_type.dart b/lib/data/model/swagger/types/swagger_request_type.dart index 7dd8061e..9d393051 100644 --- a/lib/data/model/swagger/types/swagger_request_type.dart +++ b/lib/data/model/swagger/types/swagger_request_type.dart @@ -18,7 +18,7 @@ sealed class SwaggerRequestType { case RequestPath(): type = 'pathParam'; } - return '$type - ${variable.type.toString()} ${variable.name}'; + return '$type - ${variable.type} ${variable.name}'; } } diff --git a/lib/data/model/swagger/types/swagger_type.dart b/lib/data/model/swagger/types/swagger_type.dart index 513d3f62..e43f46fd 100644 --- a/lib/data/model/swagger/types/swagger_type.dart +++ b/lib/data/model/swagger/types/swagger_type.dart @@ -24,6 +24,12 @@ sealed class SwaggerType { String? getFileImportName(DataFileType fileType); String? getDefaultReturnType(DataFileType fileType); + + String? getFullFileImport(String projectName, DataFileType fileType) { + final importName = getFileImportName(fileType); + if (importName == null) return null; + return "import 'package:$projectName/$importName';"; + } } class SwaggerVariable extends SwaggerType { @@ -65,7 +71,7 @@ class SwaggerReference extends SwaggerType { @override String getTypeDeclaration(DataFileType fileType) { - var clearName = reference; + final clearName = reference; if (fileType == DataFileType.none) { return clearName.pascalCase; } @@ -77,7 +83,7 @@ class SwaggerReference extends SwaggerType { @override String getDefaultParserClosure(DataFileType fileType) => - 'return ${getTypeDeclaration(fileType)}.fromJson(response.data);'; + 'return ${getTypeDeclaration(fileType)}.fromJson(response.data,);'; @override String? getFileImportName(DataFileType fileType) { @@ -86,7 +92,7 @@ class SwaggerReference extends SwaggerType { @override String? getFileName(DataFileType fileType) { - var clearName = reference; + final clearName = reference; if (fileType == DataFileType.none) { return '${clearName.snakeCase}.dart'; } @@ -126,11 +132,12 @@ class SwaggerArray extends SwaggerType { @override String getDefaultParserClosure(DataFileType fileType) { if (itemType.type is SwaggerReference) { - final codeLines = List.empty(growable: true); - codeLines.add('final jsonItems = response.data as List;'); - codeLines.add( - 'final items = jsonItems.map((e) => ${itemType.type.getTypeDeclaration(fileType)}.fromJson(e as Map),).toList();'); - codeLines.add('return items;'); + final codeLines = List.empty(growable: true) + ..add('final jsonItems = response.data as List;') + ..add( + 'final items = jsonItems.map((e) => ${itemType.type.getTypeDeclaration(fileType)}.fromJson(e as Map),).toList();', + ) + ..add('return items;'); return codeLines.join('\n'); } else { return 'return response.data as List<${itemType.type.getTypeDeclaration(fileType)}>;'; @@ -150,7 +157,7 @@ class SwaggerArray extends SwaggerType { itemType.type.getFileFolder(fileType); @override - String? getDefaultReturnType(fileType) => '[]'; + String? getDefaultReturnType(DataFileType fileType) => '[]'; } class SwaggerEnum extends SwaggerType { @@ -202,16 +209,24 @@ class SwaggerOperationDefault extends SwaggerType { @override String? getFileImportName(DataFileType fileType) => - 'core/arch/domain/entity/common/operation_status.dart'; + '${getFileFolder(fileType)}/${getFileName(fileType)}'; @override - String? getFileName(DataFileType fileType) => null; + String? getFileName(DataFileType fileType) => 'onix_flutter_core.dart'; @override - String? getFileFolder(DataFileType fileType) => null; + String? getFileFolder(DataFileType fileType) => 'onix_flutter_core'; @override - String? getDefaultReturnType(fileType) => 'OperationStatus.success'; + String? getDefaultReturnType(DataFileType fileType) => + 'OperationStatus.success'; + + @override + String? getFullFileImport(String projectName, DataFileType fileType) { + final importName = getFileImportName(fileType); + if (importName == null) return null; + return "import 'package:$importName';"; + } } class SwaggerFile extends SwaggerType { diff --git a/lib/data/repository/screen_repository_impl.dart b/lib/data/repository/screen_repository_impl.dart index 06f30216..d84dccd3 100644 --- a/lib/data/repository/screen_repository_impl.dart +++ b/lib/data/repository/screen_repository_impl.dart @@ -6,7 +6,7 @@ class ScreenRepositoryImpl implements ScreenRepository { final Set _screens = {}; @override - Set get screens => _screens.map((e) => Screen.copyOf(e)).toSet(); + Set get screens => _screens.map(Screen.copyOf).toSet(); @override bool exists({required String screenName}) => @@ -29,15 +29,16 @@ class ScreenRepositoryImpl implements ScreenRepository { @override void modifyScreen(Screen screen, String oldName) { - var modifiedScreen = + final modifiedScreen = _screens.firstWhere((element) => element.name == oldName); if (modifiedScreen.exists) { return; } - _screens.remove(modifiedScreen); - _screens.add(screen); + _screens + ..remove(modifiedScreen) + ..add(screen); } @override diff --git a/lib/data/repository/swagger_repository_impl.dart b/lib/data/repository/swagger_repository_impl.dart index db626f1b..e34e62f9 100644 --- a/lib/data/repository/swagger_repository_impl.dart +++ b/lib/data/repository/swagger_repository_impl.dart @@ -1,10 +1,11 @@ -import 'package:flutter/foundation.dart'; -import 'package:onix_flutter_bricks/core/arch/domain/entity/failure/api_failure.dart'; -import 'package:onix_flutter_bricks/core/arch/domain/entity/result/result.dart'; +import 'package:onix_flutter_bricks/app/extension/logger_extension.dart'; +import 'package:onix_flutter_bricks/core/di/app.dart'; import 'package:onix_flutter_bricks/data/mapper/swagger/swagger_mapper.dart'; import 'package:onix_flutter_bricks/data/source/remote/swagger/swagger_remote_source.dart'; import 'package:onix_flutter_bricks/domain/entity/component/components.dart'; +import 'package:onix_flutter_bricks/domain/entity/failure/swagger_parser_failure.dart'; import 'package:onix_flutter_bricks/domain/repository/swagger_repository.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; class SwaggerRepositoryImpl implements SwaggerRepository { @override @@ -22,6 +23,7 @@ class SwaggerRepositoryImpl implements SwaggerRepository { final swaggerResponse = await _swaggerSource.getSwaggerComponents( url: url, ); + final sources = _swaggerMapper.mapSources(swaggerResponse); final enums = _swaggerMapper.mapEnums(swaggerResponse); final dataObjects = _swaggerMapper.mapDataObjects(swaggerResponse); @@ -33,13 +35,9 @@ class SwaggerRepositoryImpl implements SwaggerRepository { ); components = parsedComponents; return Result.success(parsedComponents); - } catch (e, trace) { - if (kDebugMode) { - print(e); - print(trace); - } - //logger.e(e, stackTrace: trace); - return Result.error(failure: SwaggerParserFailure()); + } catch (e, s) { + logger.crash(error: e, stackTrace: s, reason: 'fetchSwaggerData'); + return const Result.error(failure: SwaggerParserFailure()); } } diff --git a/lib/data/source/local/config_source/config_source_impl.dart b/lib/data/source/local/config_source/config_source_impl.dart index 9a84789a..af8182f8 100644 --- a/lib/data/source/local/config_source/config_source_impl.dart +++ b/lib/data/source/local/config_source/config_source_impl.dart @@ -8,7 +8,7 @@ import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; class ConfigSourceImpl implements ConfigSource { @override Future getConfig({required String configPath}) async { - var file = File(configPath); + final file = File(configPath); if (!file.existsSync()) { logger.d('file not exists: $configPath'); @@ -19,9 +19,11 @@ class ConfigSourceImpl implements ConfigSource { } @override - Future saveConfig( - {required Config config, required String configPath}) async { - var file = await File(configPath).create(); + Future saveConfig({ + required Config config, + required String configPath, + }) async { + final file = await File(configPath).create(); await file.writeAsString(jsonEncode(config.toJson())); } } diff --git a/lib/data/source/remote/figma/figma_remote_source_impl.dart b/lib/data/source/remote/figma/figma_remote_source_impl.dart index 6c4fbd73..51de0e4b 100644 --- a/lib/data/source/remote/figma/figma_remote_source_impl.dart +++ b/lib/data/source/remote/figma/figma_remote_source_impl.dart @@ -1,7 +1,7 @@ import 'dart:convert'; import 'package:http/http.dart' as http; -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; import 'package:onix_flutter_bricks/data/model/figma/responses/file_response/figma_file_response.dart'; import 'package:onix_flutter_bricks/data/model/figma/responses/node/figma_nodes_response.dart'; import 'package:onix_flutter_bricks/data/source/remote/figma/figma_remote_data_source.dart'; diff --git a/lib/data/source/remote/swagger/swagger_remote_source.dart b/lib/data/source/remote/swagger/swagger_remote_source.dart index 29ab30d0..4dc47a19 100644 --- a/lib/data/source/remote/swagger/swagger_remote_source.dart +++ b/lib/data/source/remote/swagger/swagger_remote_source.dart @@ -1,5 +1,6 @@ import 'package:onix_flutter_bricks/data/model/swagger/swagger_response.dart'; +// ignore: one_member_abstracts abstract interface class SwaggerRemoteSource { Future getSwaggerComponents({ required String url, diff --git a/lib/data/source/remote/swagger/swagger_remote_source_impl.dart b/lib/data/source/remote/swagger/swagger_remote_source_impl.dart index b8dcbe68..70a74563 100644 --- a/lib/data/source/remote/swagger/swagger_remote_source_impl.dart +++ b/lib/data/source/remote/swagger/swagger_remote_source_impl.dart @@ -14,12 +14,14 @@ import 'package:onix_flutter_bricks/data/model/swagger/tag/swagger_tag_response. import 'package:onix_flutter_bricks/data/source/remote/swagger/swagger_remote_source.dart'; class SwaggerRemoteSourceImpl implements SwaggerRemoteSource { + const SwaggerRemoteSourceImpl(); + @override Future getSwaggerComponents({ required String url, }) async { - var response = await http.get(Uri.parse(url)); - var json = jsonDecode(response.body) as Map; + final response = await http.get(Uri.parse(url)); + final json = jsonDecode(response.body) as Map; ///Get Swagger version final swaggerVersion = json.getSwaggerVersion(); @@ -39,7 +41,7 @@ class SwaggerRemoteSourceImpl implements SwaggerRemoteSource { //get tags if (json.containsKey('tags')) { final tags = json.asObjectList('tags'); - for (var tag in tags) { + for (final tag in tags) { final tagModel = SwaggerTagResponse.fromJson(tag); swaggerTags.add(tagModel); } @@ -51,7 +53,7 @@ class SwaggerRemoteSourceImpl implements SwaggerRemoteSource { (path, value) { final pathRequestVariations = value as Map; final requestTags = pathRequestVariations.getTagsFromRequests(); - for (var tag in requestTags) { + for (final tag in requestTags) { final thisTag = swaggerTags.singleWhereOrNull((e) => e.name == tag); if (thisTag == null) { @@ -99,7 +101,7 @@ class SwaggerRemoteSourceImpl implements SwaggerRemoteSource { } ///Check swagger version - Map objectsMap = {}; + var objectsMap = {}; switch (swaggerVersion) { case SwaggerVersionType.swagger2: { diff --git a/lib/domain/entity/app_styles/app_styles.dart b/lib/domain/entity/app_styles/app_styles.dart index 6795aaa2..0b7a0a7f 100644 --- a/lib/domain/entity/app_styles/app_styles.dart +++ b/lib/domain/entity/app_styles/app_styles.dart @@ -1,4 +1,4 @@ -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; import 'package:recase/recase.dart'; abstract class AppStyle { @@ -11,7 +11,7 @@ abstract class AppStyle { }); bool validate() { - bool valid = true; + var valid = true; var newName = name; if (!AppConsts.figmaStylesFirstCharValidChars diff --git a/lib/domain/entity/app_styles/app_text_style.dart b/lib/domain/entity/app_styles/app_text_style.dart index 594f21a5..60b2cfa3 100644 --- a/lib/domain/entity/app_styles/app_text_style.dart +++ b/lib/domain/entity/app_styles/app_text_style.dart @@ -40,6 +40,9 @@ class AppTextStyle extends AppStyle { @override String toString() { - return 'FontFamily: $fontFamily, fontSize: $fontSize, fontWeight: $fontWeight, letterSpacing: $letterSpacing${color.isNotEmpty ? ', color: $color' : ''}'; + return 'FontFamily: $fontFamily, fontSize: $fontSize, ' + 'fontWeight: $fontWeight, ' + 'letterSpacing: $letterSpacing${color.isNotEmpty ? ', ' + 'color: $color' : ''},'; } } diff --git a/lib/domain/entity/component/data_object_component.dart b/lib/domain/entity/component/data_object_component.dart index 6b937648..fa8ba117 100644 --- a/lib/domain/entity/component/data_object_component.dart +++ b/lib/domain/entity/component/data_object_component.dart @@ -47,7 +47,7 @@ class DataObjectComponent with _$DataObjectComponent { String projectName, DataFileType type, ) { - final imports = _getImports(projectName, type); + final imports = Set.of(_getImports(projectName, type)); late ClassBuilder classBuilder; switch (type) { case DataFileType.request: @@ -99,42 +99,54 @@ class DataObjectComponent with _$DataObjectComponent { fileReference.getTypeDeclaration(DataFileType.response); final requestName = fileReference.getTypeDeclaration(DataFileType.request); final entityName = fileReference.getTypeDeclaration(DataFileType.entity); - final codeLines = List.empty(growable: true); + final imports = {} + ..addAll( + _getImports( + projectName, + DataFileType.response, + createResponseToEntityMapper: createResponseToEntityMapper, + createEntityToRequestMapper: createEntityToRequestMapper, + ), + ) + ..addAll( + _getImports( + projectName, + DataFileType.entity, + createResponseToEntityMapper: createResponseToEntityMapper, + createEntityToRequestMapper: createEntityToRequestMapper, + ), + ) + ..add( + "import 'package:onix_flutter_core/onix_flutter_core.dart';", + ); ///Add common imports if (createResponseToEntityMapper) { codeLines.add( - 'import \'package:$projectName/${fileReference.getFileImportName(DataFileType.response)}\';'); + "import 'package:$projectName/${fileReference.getFileImportName(DataFileType.response)}';", + ); } if (createEntityToRequestMapper) { codeLines.add( - 'import \'package:$projectName/${fileReference.getFileImportName(DataFileType.request)}\';'); + "import 'package:$projectName/${fileReference.getFileImportName(DataFileType.request)}';", + ); } - codeLines.add( - 'import \'package:$projectName/${fileReference.getFileImportName(DataFileType.entity)}\';'); - codeLines.addAll( - _getImports( - projectName, - DataFileType.response, - createResponseToEntityMapper: createResponseToEntityMapper, - createEntityToRequestMapper: createEntityToRequestMapper, - ), - ); - codeLines.addAll(_getImports(projectName, DataFileType.entity, - createResponseToEntityMapper: createResponseToEntityMapper, - createEntityToRequestMapper: createEntityToRequestMapper)); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/common/converter/mapper.dart\';'); + codeLines + ..add( + "import 'package:$projectName/${fileReference.getFileImportName(DataFileType.entity)}';", + ) + ..addAll(imports); ///Add imports to different variables and their mappers - for (var variable in variables) { + for (final variable in variables) { final ref = variable.type.getSwaggerObjectReference(); if (ref != null) { final variableImportName = ref.getTypeDeclaration(DataFileType.none).snakeCase; codeLines.add( - 'import \'package:$projectName/data/mapper/$variableImportName/${variableImportName}_mapper.dart\';'); + "import 'package:$projectName/data/mapper/$variableImportName/${variableImportName}_mapper.dart';", + ); } } codeLines.addNewLine(); @@ -143,85 +155,100 @@ class DataObjectComponent with _$DataObjectComponent { ///Inner mapper class declaration ///Response to Entity if (createResponseToEntityMapper) { - codeLines.add( - 'class _Map${classNamePrefix}ResponseToEntity implements Mapper<$responseName, $entityName> {'); - codeLines.addNewLine(); - codeLines.add('const _Map${classNamePrefix}ResponseToEntity();'); - codeLines.add('@override'); - - ///Mapper functions - codeLines.add('$entityName map($responseName from) {'); - - ///Declare inner objects mapper variables - codeLines.addAll(_getInnerMapperVariables()); - - ///return function - codeLines.add('return $entityName('); - - ///Use inner variable mapper for inner variables - codeLines.addAll( - _getMapperObjectVariablesContent(MapperType.mapResponseToEntity)); - - codeLines.add(');'); - codeLines.add('}'); - codeLines.add('}'); - codeLines.addNewLine(); + final objects = + _getMapperObjectVariablesContent(MapperType.mapResponseToEntity); + final classModifier = objects.isEmpty ? 'const ' : ''; + + codeLines + ..add( + 'class _Map${classNamePrefix}ResponseToEntity implements Mapper<$responseName, $entityName> {', + ) + ..addNewLine() + ..add('const _Map${classNamePrefix}ResponseToEntity();') + ..add('@override') + + ///Mapper functions + ..add('$entityName map($responseName from,) {') + + ///Declare inner objects mapper variables + ..addAll(_getInnerMapperVariables()) + + ///return function + ..add('return $classModifier$entityName(') + + ///Use inner variable mapper for inner variables + ..addAll(objects) + ..add(');') + ..add('}') + ..add('}') + ..addNewLine(); } ///Entity to Request if (createEntityToRequestMapper) { - codeLines.add( - 'class _Map${classNamePrefix}EntityToRequest implements Mapper<$entityName, $requestName> {'); - codeLines.addNewLine(); - codeLines.add('const _Map${classNamePrefix}EntityToRequest();'); - codeLines.add('@override'); - - ///Mapper functions - codeLines.add('$requestName map($entityName from) {'); - - ///Declare inner objects mapper variables - codeLines.addAll(_getInnerMapperVariables()); - - ///return function - codeLines.add('return $requestName('); - - ///Use inner variable mapper for inner variables - codeLines.addAll( - _getMapperObjectVariablesContent(MapperType.mapEntityToRequest)); - codeLines.add(');'); - codeLines.add('}'); - codeLines.add('}'); + final objects = + _getMapperObjectVariablesContent(MapperType.mapEntityToRequest); + final classModifier = objects.isEmpty ? 'const ' : ''; + + codeLines + ..add( + 'class _Map${classNamePrefix}EntityToRequest implements Mapper<$entityName, $requestName> {', + ) + ..addNewLine() + ..add('const _Map${classNamePrefix}EntityToRequest();') + ..add('@override') + + ///Mapper functions + ..add('$requestName map($entityName from,) {') + + ///Declare inner objects mapper variables + ..addAll(_getInnerMapperVariables()) + + ///return function + ..add('return $classModifier$requestName(') + + ///Use inner variable mapper for inner variables + ..addAll(objects) + ..add(');') + ..add('}') + ..add('}'); } - codeLines.addNewLine(); + codeLines + ..addNewLine() - ///Main mapper class declaration - codeLines.add('class ${classNamePrefix}Mappers {'); + ///Main mapper class declaration + ..add('class ${classNamePrefix}Mappers {'); if (createResponseToEntityMapper) { codeLines.add( - 'final _mapResponseToEntity = const _Map${classNamePrefix}ResponseToEntity();'); + 'final _mapResponseToEntity = const _Map${classNamePrefix}ResponseToEntity();', + ); } if (createEntityToRequestMapper) { codeLines.add( - 'final _mapEntityToRequest = const _Map${classNamePrefix}EntityToRequest();'); + 'final _mapEntityToRequest = const _Map${classNamePrefix}EntityToRequest();', + ); } codeLines.addNewLine(); if (createResponseToEntityMapper) { - codeLines.add('$entityName mapResponseToEntity($responseName from) =>'); - codeLines.add('_mapResponseToEntity.map(from);'); + codeLines + ..add('$entityName mapResponseToEntity($responseName from,) =>') + ..add('_mapResponseToEntity.map(from);'); } codeLines.addNewLine(); if (createEntityToRequestMapper) { - codeLines.add('$requestName mapEntityToRequest($entityName from) =>'); - codeLines.add('_mapEntityToRequest.map(from);'); + codeLines + ..add('$requestName mapEntityToRequest($entityName from,) =>') + ..add('_mapEntityToRequest.map(from);'); } - codeLines.add('}'); - codeLines.addNewLine(); + codeLines + ..add('}') + ..addNewLine(); return codeLines.join('\n'); } List _getInnerMapperVariables() { final codeLines = {}; - for (var variable in variables) { + for (final variable in variables) { if (variable.type is SwaggerReference) { final reference = variable.type as SwaggerReference; codeLines.add(reference.getReferenceMapperDeclaration(private: false)); @@ -239,7 +266,7 @@ class DataObjectComponent with _$DataObjectComponent { List _getMapperObjectVariablesContent(MapperType type) { final codeLines = List.empty(growable: true); - for (var variable in variables) { + for (final variable in variables) { final variableName = ReservedWordProcessor.checkAndReplaceReservedWord(variable.name) .camelCase; @@ -254,7 +281,8 @@ class DataObjectComponent with _$DataObjectComponent { ); } else { codeLines.add( - '$variableName: (from.$variableName != null) ? ${name.camelCase}Mappers.${type.name}(from.$variableName!) : ${variable.type.getDefaultReturnType(DataFileType.entity)},'); + '$variableName: (from.$variableName != null) ? ${name.camelCase}Mappers.${type.name}(from.$variableName!) : ${variable.type.getDefaultReturnType(DataFileType.entity)},', + ); } } else if (variable.type is SwaggerArray) { final array = variable.type as SwaggerArray; @@ -263,17 +291,20 @@ class DataObjectComponent with _$DataObjectComponent { final className = reference.getTypeDeclaration(DataFileType.none); if (variable.isRequired || type == MapperType.mapEntityToRequest) { codeLines.add( - '$variableName: from.$variableName.map(${className.camelCase}Mappers.${type.name},).toList(),'); + '$variableName: from.$variableName.map(${className.camelCase}Mappers.${type.name},).toList(),', + ); } else { codeLines.add( - '$variableName: (from.$variableName != null) ? from.$variableName!.map(${className.camelCase}Mappers.${type.name},).toList() : [],'); + '$variableName: (from.$variableName != null) ? from.$variableName!.map(${className.camelCase}Mappers.${type.name},).toList() : [],', + ); } } else { if (variable.isRequired || type == MapperType.mapEntityToRequest) { codeLines.add('$variableName: from.$variableName,'); } else { codeLines.add( - '$variableName: from.$variableName ?? ${variable.type.getDefaultReturnType(DataFileType.entity)},'); + '$variableName: from.$variableName ?? ${variable.type.getDefaultReturnType(DataFileType.entity)},', + ); } } } else { @@ -281,7 +312,8 @@ class DataObjectComponent with _$DataObjectComponent { codeLines.add('$variableName: from.$variableName,'); } else { codeLines.add( - '$variableName: from.$variableName ?? ${variable.type.getDefaultReturnType(DataFileType.entity)},'); + '$variableName: from.$variableName ?? ${variable.type.getDefaultReturnType(DataFileType.entity)},', + ); } } } @@ -295,28 +327,30 @@ class DataObjectComponent with _$DataObjectComponent { bool? createEntityToRequestMapper, bool? createResponseToEntityMapper, }) { - final imports = List.empty(growable: true); + final imports = List.empty(growable: true); final notNullImports = variables.where((e) => e.type.getFileImportName(type) != null); - for (var e in notNullImports) { + for (final e in notNullImports) { if (createEntityToRequestMapper != null && createResponseToEntityMapper != null) { if (type == DataFileType.request) { if (createEntityToRequestMapper) { - imports.add(e.type.getFileImportName(type) ?? ''); + imports.add(e.type); } } else if (type == DataFileType.response) { if (createResponseToEntityMapper) { - imports.add(e.type.getFileImportName(type) ?? ''); + imports.add(e.type); } } else { - imports.add(e.type.getFileImportName(type) ?? ''); + imports.add(e.type); } } else { - imports.add(e.type.getFileImportName(type) ?? ''); + imports.add(e.type); } } - return imports.map((e) => 'import \'package:$projectName/$e\';').toList(); + return imports + .map((e) => e.getFullFileImport(projectName, type) ?? '') + .toList(); } List _getFreezedConstructorProperties( @@ -362,7 +396,7 @@ class DataObjectComponent with _$DataObjectComponent { final requiredSuffix = e.isRequired ? '' : '?'; final name = ReservedWordProcessor.checkAndReplaceReservedWord(e.name).camelCase; - return '@JsonKey(name: \'${e.name}\')\nfinal ${e.type.getTypeDeclaration(type)}$requiredSuffix $name;'; + return "@JsonKey(name: '${e.name}')\nfinal ${e.type.getTypeDeclaration(type)}$requiredSuffix $name;"; }).toList(); } } diff --git a/lib/domain/entity/component/enum_param_component.dart b/lib/domain/entity/component/enum_param_component.dart index 9c3dd909..b38dc396 100644 --- a/lib/domain/entity/component/enum_param_component.dart +++ b/lib/domain/entity/component/enum_param_component.dart @@ -21,10 +21,10 @@ class EnumParamComponent with _$EnumParamComponent { '${getFolderPath(projectRoot)}/${type.getFileName(DataFileType.none)}'; String getEnumFileBody() { - final codeLines = List.empty(growable: true); - codeLines.addNewLine(); - codeLines.add('enum ${type.getTypeDeclaration(DataFileType.none)} {'); - for (var e in type.enumValues) { + final codeLines = List.empty(growable: true) + ..addNewLine() + ..add('enum ${type.getTypeDeclaration(DataFileType.none)} {'); + for (final e in type.enumValues) { codeLines.add('${e.camelCase},'); } codeLines.add('}'); diff --git a/lib/domain/entity/component/request_component.dart b/lib/domain/entity/component/request_component.dart index d47c3161..a1826db2 100644 --- a/lib/domain/entity/component/request_component.dart +++ b/lib/domain/entity/component/request_component.dart @@ -35,14 +35,15 @@ class RequestComponent with _$RequestComponent { ///Write REST API ath declaration String getVariableDeclaration() { - ///If there pathParams - build declaration as functions and pass params into the path + /// If there pathParams - build declaration as functions and + /// pass params into the path if (pathParams.isNotEmpty) { final codeLines = List.empty(growable: true); final paramsDeclaration = pathParams .map( (e) => e.getParamBodyDeclaration( DataFileType.request, - true, + isRequiredRequestBody: true, ), ) .join('\n'); @@ -50,15 +51,15 @@ class RequestComponent with _$RequestComponent { .add('String _${operationId.camelCase}({$paramsDeclaration}) =>'); final names = pathParams.map((e) => e.name); var pathWithParams = path; - for (var e in names) { + for (final e in names) { pathWithParams = pathWithParams.replaceAll('{$e}', '\$${e.camelCase}'); } - codeLines.add('\'$pathWithParams\';'); + codeLines.add("'$pathWithParams';"); return codeLines.join('\n'); } ///Build regular declaration - return 'static const _${operationId.camelCase} = \'$path\';'; + return "static const _${operationId.camelCase} = '$path';"; } ///Create declaration for request in source interface @@ -90,14 +91,16 @@ class RequestComponent with _$RequestComponent { response.type.getTypeDeclaration(DataFileType.response); final responseClosure = response.type.getDefaultParserClosure(DataFileType.response); - codeLines.addAll(_descriptionArray()); + codeLines + ..addAll(_descriptionArray()) - ///Function start - codeLines.add('@override'); + ///Function start + ..add('@override') - ///Declare a new function - codeLines - .add('Future> ${operationId.camelCase}('); + ///Declare a new function + ..add( + 'Future> ${operationId.camelCase}(', + ); ///Create function input params final functionParams = _buildFunctionParams(DataFileType.request); @@ -115,33 +118,34 @@ class RequestComponent with _$RequestComponent { final multipartFiles = multipartBody.where( (e) => e.type is SwaggerFile, ); - for (var e in multipartFiles) { + for (final e in multipartFiles) { codeLines.add( 'final ${e.getNameDeclaration()}MultipartFile = await MultipartFile.fromFile(${e.getNameDeclaration()});'); } ///create form data codeLines.add('final formData = FormData.fromMap({'); - for (var e in multipartBody) { + for (final e in multipartBody) { if (e.type is SwaggerFile) { - codeLines - .add('\'${e.name}\': ${e.getNameDeclaration()}MultipartFile,'); + codeLines.add("'${e.name}': ${e.getNameDeclaration()}MultipartFile,"); } else { - codeLines.add('\'${e.name}\': ${e.getNameDeclaration()},'); + codeLines.add("'${e.name}': ${e.getNameDeclaration()},"); } } - codeLines.add('},);'); - codeLines.addNewLine(); + codeLines + ..add('},);') + ..addNewLine(); } ///If query params not empty - create query parameter variables if (queryParams.isNotEmpty) { codeLines.add('final queryParams = {'); - for (var e in queryParams) { - codeLines.add('\'${e.name}\': ${e.getNameDeclaration()},'); + for (final e in queryParams) { + codeLines.add("'${e.name}': ${e.getNameDeclaration()},"); } - codeLines.add('};'); - codeLines.addNewLine(); + codeLines + ..add('};') + ..addNewLine(); } ///If create a new request @@ -182,17 +186,18 @@ class RequestComponent with _$RequestComponent { if (queryParams.isNotEmpty) { codeLines.add('queryParameters: queryParams,'); } - codeLines.add(');'); + codeLines + ..add(');') - ///End request build - codeLines.addNewLine(); + ///End request build + ..addNewLine() - ///Call dio request processor - codeLines.add('return _dioRequestProcessor.processRequest('); - codeLines.add('onRequest: () => request,'); - codeLines.add('onResponse: (response) {'); - codeLines.add(responseClosure); - codeLines.add('},);}'); + ///Call dio request processor + ..add('return _dioRequestProcessor.processRequest(') + ..add('onRequest: () => request,') + ..add('onResponse: (response) {') + ..add(responseClosure) + ..add('},);}'); return codeLines.join('\n'); } @@ -200,8 +205,9 @@ class RequestComponent with _$RequestComponent { String getRepoDeclarationBody() { final codeLines = List.empty(growable: true); final returnType = response.type.getTypeDeclaration(DataFileType.entity); - codeLines.addAll(_descriptionArray()); - codeLines.add('Future> ${operationId.camelCase}('); + codeLines + ..addAll(_descriptionArray()) + ..add('Future> ${operationId.camelCase}('); ///Create function input params final functionParams = _buildFunctionParams(DataFileType.entity); @@ -218,10 +224,10 @@ class RequestComponent with _$RequestComponent { String getRepoImplementationBody(String repoName) { final returnType = response.type.getTypeDeclaration(DataFileType.entity); - final codeLines = List.empty(growable: true); - codeLines.add('@override'); - codeLines.addAll(_descriptionArray()); - codeLines.add('Future> ${operationId.camelCase}('); + final codeLines = List.empty(growable: true) + ..add('@override') + ..addAll(_descriptionArray()) + ..add('Future> ${operationId.camelCase}('); ///Create function input params final functionParams = _buildFunctionParams(DataFileType.entity); @@ -232,15 +238,17 @@ class RequestComponent with _$RequestComponent { if (functionParams.isNotEmpty) { codeLines.add('}'); } - codeLines.add(') async {'); - codeLines.add('try {'); + codeLines + ..add(') async {') + ..add('try {'); if (requestBody != null) { if (requestBody!.type is SwaggerReference) { final body = requestBody!.type as SwaggerReference; final requestBodyType = body.getTypeDeclaration(DataFileType.none); final requestBodyName = requestBody!.getNameDeclaration(); codeLines.add( - 'final ${requestBodyType.camelCase}RequestBody = _${requestBodyType.camelCase}Mappers.mapEntityToRequest($requestBodyName);'); + 'final ${requestBodyType.camelCase}RequestBody = _${requestBodyType.camelCase}Mappers.mapEntityToRequest($requestBodyName);', + ); } else if (requestBody!.type is SwaggerArray) { final array = requestBody!.type as SwaggerArray; if (array.itemType.type is SwaggerReference) { @@ -248,53 +256,60 @@ class RequestComponent with _$RequestComponent { final requestBodyName = requestBody!.getNameDeclaration(); final requestBodyType = ref.getTypeDeclaration(DataFileType.none); codeLines.add( - 'final ${requestBodyType.camelCase}RequestBody = $requestBodyName.map(_${requestBodyType.camelCase}Mappers.mapEntityToRequest,).toList();'); + 'final ${requestBodyType.camelCase}RequestBody = $requestBodyName.map(_${requestBodyType.camelCase}Mappers.mapEntityToRequest,).toList();', + ); } } } codeLines.add( 'final result = await _${repoName}Source.${operationId.camelCase}('); - //TODO final sourceCallParams = _buildSourceCallParams(DataFileType.none); - codeLines.add(sourceCallParams); - codeLines.add(');'); - codeLines.addNewLine(); - codeLines.add('if (result.isSuccess()) {'); + codeLines + ..add(sourceCallParams) + ..add(');') + ..addNewLine() + ..add('if (result.isSuccess()) {'); if (response.type is SwaggerReference) { final ref = response.type as SwaggerReference; final responseName = ref.getTypeDeclaration(DataFileType.none).camelCase; - codeLines.add( - 'final ${responseName}Object = _${responseName}Mappers.mapResponseToEntity(result.data);'); - codeLines.add('return Result.success(${responseName}Object);'); + codeLines + ..add( + 'final ${responseName}Object = _${responseName}Mappers.mapResponseToEntity(result.data);', + ) + ..add('return Result.success(${responseName}Object);'); } else if (response.type is SwaggerArray) { final array = response.type as SwaggerArray; if (array.itemType.type is SwaggerReference) { final ref = array.itemType.type as SwaggerReference; final responseName = ref.getTypeDeclaration(DataFileType.none).camelCase; - codeLines.add( - 'final ${responseName}Objects = result.data.map(_${responseName}Mappers.mapResponseToEntity,).toList();'); - codeLines.add('return Result.success(${responseName}Objects);'); + codeLines + ..add( + 'final ${responseName}Objects = result.data.map(_${responseName}Mappers.mapResponseToEntity,).toList();', + ) + ..add('return Result.success(${responseName}Objects);'); } else { codeLines.add('return Result.success(result.data);'); } } else { codeLines.add('return Result.success(result.data);'); } - codeLines.add('} else {'); - codeLines.add( - 'return Result.error(failure: MapCommonServerError.getServerFailureDetails(result),);'); - codeLines.add('}'); - - codeLines.add('} catch (e, trace) {'); - codeLines.add( - 'logger.crash(reason: \'${operationId.camelCase}\', error: e, stackTrace: trace,);'); - codeLines.add('return Result.error('); - codeLines.add('failure: ApiFailure('); - codeLines.add('ServerFailure.exception,'); - codeLines.add('message: e.toString(),'); - codeLines.add('),);}'); - codeLines.add('}'); + codeLines + ..add('} else {') + ..add( + 'return Result.error(failure: MapCommonServerError.getServerFailureDetails(result),);', + ) + ..add('}') + ..add('} catch (e, trace) {') + ..add( + "logger.crash(reason: '${operationId.camelCase}', error: e, stackTrace: trace,);", + ) + ..add('return Result.error(') + ..add('failure: ApiFailure(') + ..add('ServerFailure.exception,') + ..add('message: e.toString(),') + ..add('),);}') + ..add('}'); return codeLines.join('\n'); } @@ -302,36 +317,46 @@ class RequestComponent with _$RequestComponent { String _buildFunctionParams(DataFileType fileType) { final codeLines = List.empty(growable: true); if (requestBody != null) { - codeLines.add(requestBody?.getParamBodyDeclaration( - fileType, - true, - ) ?? - ''); + codeLines.add( + requestBody?.getParamBodyDeclaration( + fileType, + isRequiredRequestBody: true, + ) ?? + '', + ); } if (multipartBody.isNotEmpty) { - for (var e in multipartBody) { - codeLines.add(e.getParamBodyDeclaration( - fileType, - true, - )); + for (final e in multipartBody) { + codeLines.add( + e.getParamBodyDeclaration( + fileType, + isRequiredRequestBody: true, + ), + ); } } if (queryParams.isNotEmpty) { - for (var e in queryParams) { - codeLines.add(e.getParamBodyDeclaration( - fileType, - false, - )); + for (final e in queryParams) { + codeLines.add( + e.getParamBodyDeclaration( + fileType, + isRequiredRequestBody: false, + ), + ); } } if (pathParams.isNotEmpty) { - for (var e in pathParams) { - codeLines.add(e.getParamBodyDeclaration( - fileType, - false, - )); + for (final e in pathParams) { + codeLines.add( + e.getParamBodyDeclaration( + fileType, + isRequiredRequestBody: false, + ), + ); } } + + codeLines.sort((a, b) => b.startsWith('required') ? 1 : -1); return codeLines.join('\n'); } @@ -348,24 +373,25 @@ class RequestComponent with _$RequestComponent { DataFileType.none, ); codeLines.add( - '$requestBodyName: ${requestBodyType.camelCase}RequestBody,'); + '$requestBodyName: ${requestBodyType.camelCase}RequestBody,', + ); } } else { codeLines.add('$requestBodyName: ${requestBody!.name.camelCase},'); } } if (multipartBody.isNotEmpty) { - for (var e in multipartBody) { + for (final e in multipartBody) { codeLines.add('${e.getNameDeclaration()}: ${e.getNameDeclaration()},'); } } if (queryParams.isNotEmpty) { - for (var e in queryParams) { + for (final e in queryParams) { codeLines.add('${e.getNameDeclaration()}: ${e.getNameDeclaration()},'); } } if (pathParams.isNotEmpty) { - for (var e in pathParams) { + for (final e in pathParams) { codeLines.add('${e.getNameDeclaration()}: ${e.getNameDeclaration()},'); } } diff --git a/lib/domain/entity/component/request_param_component.dart b/lib/domain/entity/component/request_param_component.dart index 1194e777..20975aad 100644 --- a/lib/domain/entity/component/request_param_component.dart +++ b/lib/domain/entity/component/request_param_component.dart @@ -14,9 +14,9 @@ sealed class RequestParamComponent { }); String getParamBodyDeclaration( - DataFileType fileType, - bool isRequiredRequestBody, - ) { + DataFileType fileType, { + required bool isRequiredRequestBody, + }) { var requiredCopy = isRequired; if (isRequiredRequestBody) { requiredCopy = isRequiredRequestBody; diff --git a/lib/domain/entity/component/source_component.dart b/lib/domain/entity/component/source_component.dart index 939cf58e..3226cf21 100644 --- a/lib/domain/entity/component/source_component.dart +++ b/lib/domain/entity/component/source_component.dart @@ -40,124 +40,110 @@ class SourceComponent with _$SourceComponent { '${getRepositoryImplFolderPath(projectRoot)}/${name.snakeCase}_repository_impl.dart'; String getDeclarationImport(String projectName) => - 'import \'package:$projectName/data/source/remote/${name.snakeCase}/${name.snakeCase}_source.dart\';'; + "import 'package:$projectName/data/source/remote/${name.snakeCase}/${name.snakeCase}_source.dart';"; String getImplementationImport(String projectName) => - 'import \'package:$projectName/data/source/remote/${name.snakeCase}/${name.snakeCase}_source_impl.dart\';'; + "import 'package:$projectName/data/source/remote/${name.snakeCase}/${name.snakeCase}_source_impl.dart';"; String getRepoDeclarationImport(String projectName) => - 'import \'package:$projectName/domain/repository/${name.snakeCase}/${name.snakeCase}_repository.dart\';'; + "import 'package:$projectName/domain/repository/${name.snakeCase}/${name.snakeCase}_repository.dart';"; String getRepoImplementationImport(String projectName) => - 'import \'package:$projectName/data/repository/${name.snakeCase}/${name.snakeCase}_repository_impl.dart\';'; + "import 'package:$projectName/data/repository/${name.snakeCase}/${name.snakeCase}_repository_impl.dart';"; - String getDeclarationBody(String projectName) { + String getSourceDeclarationBody(String projectName) { final codeLines = List.empty(growable: true); - codeLines.add('import \'package:dio/dio.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/entity/common/data_response.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/entity/common/operation_status.dart\';'); ///Add Imports final modelImports = _buildSourceImports(projectName); - codeLines.add(modelImports); - - codeLines.addNewLine(); - codeLines.add('abstract interface class ${name.pascalCase}Source {'); - codeLines.addNewLine(); - for (var e in requests) { - codeLines.add(e.getRequestDeclaration()); - codeLines.addNewLine(); + codeLines + ..add(modelImports) + ..addNewLine() + ..add('abstract interface class ${name.pascalCase}Source {') + ..addNewLine(); + for (final e in requests) { + codeLines + ..add(e.getRequestDeclaration()) + ..addNewLine(); } - codeLines.add('}'); - codeLines.addNewLine(); + codeLines + ..add('}') + ..addNewLine(); return codeLines.join('\n'); } - String getImplementationBody(String projectName) { - final codeLines = List.empty(growable: true); - codeLines.add( - 'import \'package:$projectName/core/arch/data/remote/clients/dio/api_client.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/entity/common/operation_status.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/data/remote/clients/dio/dio_request_processor/dio_request_processor.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/entity/common/data_response.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/entity/common/operation_status.dart\';'); - codeLines.add('import \'package:dio/dio.dart\';'); - codeLines.add( - 'import \'package:$projectName/data/source/remote/${name.snakeCase}/${name.snakeCase}_source.dart\';'); + String getSourceImplementationBody(String projectName) { + final codeLines = List.empty(growable: true) + ..add("import 'package:dio/dio.dart';") + ..add( + "import 'package:$projectName/data/source/remote/${name.snakeCase}/${name.snakeCase}_source.dart';", + ); ///Add imports final modelImports = _buildSourceImports(projectName); - codeLines.add(modelImports); - - codeLines.add( - 'class ${name.pascalCase}SourceImpl implements ${name.pascalCase}Source {'); - codeLines.addNewLine(); - for (var e in requests) { + codeLines + ..add(modelImports) + ..add( + 'class ${name.pascalCase}SourceImpl implements ${name.pascalCase}Source {', + ) + ..addNewLine(); + for (final e in requests) { codeLines.add(e.getVariableDeclaration()); } - codeLines.addNewLine(); - codeLines.add('final ApiClient _apiClient;'); - codeLines.add('final DioRequestProcessor _dioRequestProcessor;'); - codeLines.addNewLine(); - codeLines.add( - 'const ${name.pascalCase}SourceImpl(this._apiClient, this._dioRequestProcessor);'); - codeLines.addNewLine(); - for (var e in requests) { - codeLines.add(e.getRequestBody()); - codeLines.addNewLine(); + codeLines + ..addNewLine() + ..add('final ApiClient _apiClient;') + ..add('final DioRequestProcessor _dioRequestProcessor;') + ..addNewLine() + ..add( + 'const ${name.pascalCase}SourceImpl(this._apiClient, this._dioRequestProcessor,);', + ) + ..addNewLine(); + for (final e in requests) { + codeLines + ..add(e.getRequestBody()) + ..addNewLine(); } - codeLines.addNewLine(); - codeLines.add('}'); - codeLines.addNewLine(); + codeLines + ..addNewLine() + ..add('}') + ..addNewLine(); return codeLines.join('\n'); } String getRepoDeclarationBody(String projectName) { final codeLines = List.empty(growable: true); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/entity/common/result.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/entity/common/operation_status.dart\';'); final modelImports = _buildRepositoryImports(projectName); - codeLines.add(modelImports); - codeLines.add('abstract interface class ${name.pascalCase}Repository {'); - codeLines.addNewLine(); - for (var e in requests) { - codeLines.add(e.getRepoDeclarationBody()); - codeLines.addNewLine(); + codeLines + ..add(modelImports) + ..add('abstract interface class ${name.pascalCase}Repository {') + ..addNewLine(); + for (final e in requests) { + codeLines + ..add(e.getRepoDeclarationBody()) + ..addNewLine(); } - codeLines.add('}'); - codeLines.addNewLine(); + codeLines + ..add('}') + ..addNewLine(); return codeLines.join('\n'); } String getRepoImplementationBody(String projectName) { - final codeLines = List.empty(growable: true); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/entity/common/result.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/entity/common/operation_status.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/domain/entity/failure/api_failure.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/logger/app_logger_impl.dart\';'); - codeLines.add( - 'import \'package:$projectName/core/arch/data/remote/base/map_common_server_error.dart\';'); + final codeLines = {}; final modelImports = _buildRepositoryImports(projectName); - codeLines.add(modelImports); - codeLines.add(getRepoDeclarationImport(projectName)); - codeLines.add(getDeclarationImport(projectName)); + codeLines + ..add( + "import 'package:$projectName/core/arch/logger/app_logger_impl.dart';", + ) + ..add(modelImports) + ..add(getRepoDeclarationImport(projectName)) + ..add(getDeclarationImport(projectName)); ///Get imports for request object mappers final mapperImports = List.empty(growable: true); - for (var e in requests) { + for (final e in requests) { final requestBody = e.requestBody; ///Add request body import @@ -183,14 +169,16 @@ class SourceComponent with _$SourceComponent { } } - codeLines.addAll(mapperImports); - codeLines.add( - 'class ${name.pascalCase}RepositoryImpl implements ${name.pascalCase}Repository {'); - codeLines.add('final ${name.pascalCase}Source _${name.camelCase}Source;'); + codeLines + ..addAll(mapperImports) + ..add( + 'class ${name.pascalCase}RepositoryImpl implements ${name.pascalCase}Repository {', + ) + ..add('final ${name.pascalCase}Source _${name.camelCase}Source;'); ///Declare mappers for request objects final mapperVariables = List.empty(growable: true); - for (var e in requests) { + for (final e in requests) { final requestBody = e.requestBody; if (requestBody != null) { final requestReference = requestBody.type.getSwaggerObjectReference(); @@ -213,37 +201,39 @@ class SourceComponent with _$SourceComponent { } } } - codeLines.addAll(mapperVariables); - - codeLines.add( - '${name.pascalCase}RepositoryImpl(this._${name.camelCase}Source);'); - - codeLines.addNewLine(); - for (var e in requests) { - codeLines.add(e.getRepoImplementationBody(name.camelCase)); - codeLines.addNewLine(); + codeLines + ..addAll(mapperVariables) + ..add('${name.pascalCase}RepositoryImpl(this._${name.camelCase}Source,);') + ..addNewLine(); + for (final e in requests) { + codeLines + ..add(e.getRepoImplementationBody(name.camelCase)) + ..addNewLine(); } - codeLines.add('}'); - codeLines.addNewLine(); + codeLines + ..add('}') + ..addNewLine(); return codeLines.join('\n'); } String _buildSourceImports(String projectName) { - final imports = List.empty(growable: true); - for (var request in requests) { + final imports = {} + ..add("import 'package:onix_flutter_core/onix_flutter_core.dart';"); + + for (final request in requests) { ///build response imports ///Add response body import - final responseFileImport = - request.response.type.getFileImportName(DataFileType.response); + final responseFileImport = request.response.type + .getFullFileImport(projectName, DataFileType.response); if (responseFileImport != null && !imports.contains(responseFileImport)) { imports.add(responseFileImport); } ///Add request body import if (request.requestBody != null) { - final bodyImport = - request.requestBody?.type.getFileImportName(DataFileType.request); + final bodyImport = request.requestBody?.type + .getFullFileImport(projectName, DataFileType.request); if (bodyImport != null && !imports.contains(bodyImport)) { imports.add(bodyImport); } @@ -251,8 +241,9 @@ class SourceComponent with _$SourceComponent { ///Add path params imports if (request.pathParams.isNotEmpty) { - for (var e in request.pathParams) { - final import = e.type.getFileImportName(DataFileType.request); + for (final e in request.pathParams) { + final import = + e.type.getFullFileImport(projectName, DataFileType.request); if (import != null && !imports.contains(import)) { imports.add(import); } @@ -261,8 +252,9 @@ class SourceComponent with _$SourceComponent { ///Add query params imports if (request.queryParams.isNotEmpty) { - for (var e in request.queryParams) { - final import = e.type.getFileImportName(DataFileType.request); + for (final e in request.queryParams) { + final import = + e.type.getFullFileImport(projectName, DataFileType.request); if (import != null && !imports.contains(import)) { imports.add(import); } @@ -271,32 +263,38 @@ class SourceComponent with _$SourceComponent { ///Add multipart params imports if (request.multipartBody.isNotEmpty) { - for (var e in request.multipartBody) { - final import = e.type.getFileImportName(DataFileType.request); + for (final e in request.multipartBody) { + final import = + e.type.getFullFileImport(projectName, DataFileType.request); if (import != null && !imports.contains(import)) { imports.add(import); } } } } - return imports.map((e) => 'import \'package:$projectName/$e\';').join('\n'); + return imports.map((e) => e).join('\n'); } String _buildRepositoryImports(String projectName) { - final imports = List.empty(growable: true); - for (var request in requests) { + final imports = {} + ..add("import 'package:onix_flutter_core/onix_flutter_core.dart';") + ..add( + "import 'package:onix_flutter_core_models/onix_flutter_core_models.dart';", + ); + + for (final request in requests) { ///build response imports ///Add response body import - final responseFileImport = - request.response.type.getFileImportName(DataFileType.entity); + final responseFileImport = request.response.type + .getFullFileImport(projectName, DataFileType.entity); if (responseFileImport != null && !imports.contains(responseFileImport)) { imports.add(responseFileImport); } ///Add request body import if (request.requestBody != null) { - final bodyImport = - request.requestBody?.type.getFileImportName(DataFileType.entity); + final bodyImport = request.requestBody?.type + .getFullFileImport(projectName, DataFileType.entity); if (bodyImport != null && !imports.contains(bodyImport)) { imports.add(bodyImport); } @@ -304,8 +302,9 @@ class SourceComponent with _$SourceComponent { ///Add path params imports if (request.pathParams.isNotEmpty) { - for (var e in request.pathParams) { - final import = e.type.getFileImportName(DataFileType.entity); + for (final e in request.pathParams) { + final import = + e.type.getFullFileImport(projectName, DataFileType.entity); if (import != null && !imports.contains(import)) { imports.add(import); } @@ -314,8 +313,9 @@ class SourceComponent with _$SourceComponent { ///Add query params imports if (request.queryParams.isNotEmpty) { - for (var e in request.queryParams) { - final import = e.type.getFileImportName(DataFileType.entity); + for (final e in request.queryParams) { + final import = + e.type.getFullFileImport(projectName, DataFileType.entity); if (import != null && !imports.contains(import)) { imports.add(import); } @@ -324,21 +324,22 @@ class SourceComponent with _$SourceComponent { ///Add multipart params imports if (request.multipartBody.isNotEmpty) { - for (var e in request.multipartBody) { - final import = e.type.getFileImportName(DataFileType.entity); + for (final e in request.multipartBody) { + final import = + e.type.getFullFileImport(projectName, DataFileType.entity); if (import != null && !imports.contains(import)) { imports.add(import); } } } } - return imports.map((e) => 'import \'package:$projectName/$e\';').join('\n'); + return imports.map((e) => e).join('\n'); } ///Get related object used in source requests (request and response objects) List getSourceObjects() { final components = List.empty(growable: true); - for (var request in requests) { + for (final request in requests) { ///Response object component final responseFileType = request.response.type; final reference = responseFileType.getSwaggerObjectReference(); @@ -366,7 +367,7 @@ class SourceComponent with _$SourceComponent { } //Other params if (request.multipartBody.isNotEmpty) { - for (var e in request.multipartBody) { + for (final e in request.multipartBody) { final reference = e.type.getSwaggerObjectReference(); if (reference != null) { components.add( @@ -379,7 +380,7 @@ class SourceComponent with _$SourceComponent { } } if (request.pathParams.isNotEmpty) { - for (var e in request.pathParams) { + for (final e in request.pathParams) { final reference = e.type.getSwaggerObjectReference(); if (reference != null) { components.add( @@ -392,7 +393,7 @@ class SourceComponent with _$SourceComponent { } } if (request.queryParams.isNotEmpty) { - for (var e in request.queryParams) { + for (final e in request.queryParams) { final reference = e.type.getSwaggerObjectReference(); if (reference != null) { components.add( diff --git a/lib/domain/entity/config/config.dart b/lib/domain/entity/config/config.dart index 41bb2c3e..55ec36c9 100644 --- a/lib/domain/entity/config/config.dart +++ b/lib/domain/entity/config/config.dart @@ -1,9 +1,10 @@ import 'package:freezed_annotation/freezed_annotation.dart'; -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; import 'package:onix_flutter_bricks/core/di/repository.dart'; import 'package:onix_flutter_bricks/core/di/source.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_styles.dart'; import 'package:onix_flutter_bricks/domain/entity/platforms_list/platforms_list.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/project_state_manager.dart'; import 'package:onix_flutter_bricks/domain/entity/screen/screen.dart'; import 'package:onix_flutter_bricks/util/enum/project_localization.dart'; import 'package:onix_flutter_bricks/util/enum/project_router.dart'; @@ -23,6 +24,7 @@ class Config with _$Config { @Default(false) bool projectExists, @Default('') String organization, @Default(PlatformsList()) PlatformsList platformsList, + @Default(ProjectStateManager.bloc) ProjectStateManager stateManager, @Default(false) bool flavorize, @Default('') String flavors, @Default(false) bool generateSigningKey, @@ -40,6 +42,7 @@ class Config with _$Config { @Default([]) List styles, @Default('') String swaggerUrl, + @Default(false) bool sentry, }) = _Config; const Config._(); diff --git a/lib/domain/entity/config/config.freezed.dart b/lib/domain/entity/config/config.freezed.dart index c197de44..365ed0f7 100644 --- a/lib/domain/entity/config/config.freezed.dart +++ b/lib/domain/entity/config/config.freezed.dart @@ -28,6 +28,7 @@ mixin _$Config { bool get projectExists => throw _privateConstructorUsedError; String get organization => throw _privateConstructorUsedError; PlatformsList get platformsList => throw _privateConstructorUsedError; + ProjectStateManager get stateManager => throw _privateConstructorUsedError; bool get flavorize => throw _privateConstructorUsedError; String get flavors => throw _privateConstructorUsedError; bool get generateSigningKey => throw _privateConstructorUsedError; @@ -44,6 +45,7 @@ mixin _$Config { @JsonKey(includeFromJson: false, includeToJson: false) List get styles => throw _privateConstructorUsedError; String get swaggerUrl => throw _privateConstructorUsedError; + bool get sentry => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -64,6 +66,7 @@ abstract class $ConfigCopyWith<$Res> { bool projectExists, String organization, PlatformsList platformsList, + ProjectStateManager stateManager, bool flavorize, String flavors, bool generateSigningKey, @@ -78,7 +81,8 @@ abstract class $ConfigCopyWith<$Res> { Set screens, @JsonKey(includeFromJson: false, includeToJson: false) List styles, - String swaggerUrl}); + String swaggerUrl, + bool sentry}); $PlatformsListCopyWith<$Res> get platformsList; } @@ -104,6 +108,7 @@ class _$ConfigCopyWithImpl<$Res, $Val extends Config> Object? projectExists = null, Object? organization = null, Object? platformsList = null, + Object? stateManager = null, Object? flavorize = null, Object? flavors = null, Object? generateSigningKey = null, @@ -118,6 +123,7 @@ class _$ConfigCopyWithImpl<$Res, $Val extends Config> Object? screens = null, Object? styles = null, Object? swaggerUrl = null, + Object? sentry = null, }) { return _then(_value.copyWith( branch: null == branch @@ -152,6 +158,10 @@ class _$ConfigCopyWithImpl<$Res, $Val extends Config> ? _value.platformsList : platformsList // ignore: cast_nullable_to_non_nullable as PlatformsList, + stateManager: null == stateManager + ? _value.stateManager + : stateManager // ignore: cast_nullable_to_non_nullable + as ProjectStateManager, flavorize: null == flavorize ? _value.flavorize : flavorize // ignore: cast_nullable_to_non_nullable @@ -208,6 +218,10 @@ class _$ConfigCopyWithImpl<$Res, $Val extends Config> ? _value.swaggerUrl : swaggerUrl // ignore: cast_nullable_to_non_nullable as String, + sentry: null == sentry + ? _value.sentry + : sentry // ignore: cast_nullable_to_non_nullable + as bool, ) as $Val); } @@ -236,6 +250,7 @@ abstract class _$$ConfigImplCopyWith<$Res> implements $ConfigCopyWith<$Res> { bool projectExists, String organization, PlatformsList platformsList, + ProjectStateManager stateManager, bool flavorize, String flavors, bool generateSigningKey, @@ -250,7 +265,8 @@ abstract class _$$ConfigImplCopyWith<$Res> implements $ConfigCopyWith<$Res> { Set screens, @JsonKey(includeFromJson: false, includeToJson: false) List styles, - String swaggerUrl}); + String swaggerUrl, + bool sentry}); @override $PlatformsListCopyWith<$Res> get platformsList; @@ -275,6 +291,7 @@ class __$$ConfigImplCopyWithImpl<$Res> Object? projectExists = null, Object? organization = null, Object? platformsList = null, + Object? stateManager = null, Object? flavorize = null, Object? flavors = null, Object? generateSigningKey = null, @@ -289,6 +306,7 @@ class __$$ConfigImplCopyWithImpl<$Res> Object? screens = null, Object? styles = null, Object? swaggerUrl = null, + Object? sentry = null, }) { return _then(_$ConfigImpl( branch: null == branch @@ -323,6 +341,10 @@ class __$$ConfigImplCopyWithImpl<$Res> ? _value.platformsList : platformsList // ignore: cast_nullable_to_non_nullable as PlatformsList, + stateManager: null == stateManager + ? _value.stateManager + : stateManager // ignore: cast_nullable_to_non_nullable + as ProjectStateManager, flavorize: null == flavorize ? _value.flavorize : flavorize // ignore: cast_nullable_to_non_nullable @@ -379,6 +401,10 @@ class __$$ConfigImplCopyWithImpl<$Res> ? _value.swaggerUrl : swaggerUrl // ignore: cast_nullable_to_non_nullable as String, + sentry: null == sentry + ? _value.sentry + : sentry // ignore: cast_nullable_to_non_nullable + as bool, )); } } @@ -395,6 +421,7 @@ class _$ConfigImpl extends _Config { this.projectExists = false, this.organization = '', this.platformsList = const PlatformsList(), + this.stateManager = ProjectStateManager.bloc, this.flavorize = false, this.flavors = '', this.generateSigningKey = false, @@ -409,7 +436,8 @@ class _$ConfigImpl extends _Config { final Set screens = const {}, @JsonKey(includeFromJson: false, includeToJson: false) final List styles = const [], - this.swaggerUrl = ''}) + this.swaggerUrl = '', + this.sentry = false}) : _signingVars = signingVars, _screens = screens, _styles = styles, @@ -444,6 +472,9 @@ class _$ConfigImpl extends _Config { final PlatformsList platformsList; @override @JsonKey() + final ProjectStateManager stateManager; + @override + @JsonKey() final bool flavorize; @override @JsonKey() @@ -504,10 +535,13 @@ class _$ConfigImpl extends _Config { @override @JsonKey() final String swaggerUrl; + @override + @JsonKey() + final bool sentry; @override String toString() { - return 'Config(branch: $branch, localVersion: $localVersion, remoteVersion: $remoteVersion, projectPath: $projectPath, projectName: $projectName, projectExists: $projectExists, organization: $organization, platformsList: $platformsList, flavorize: $flavorize, flavors: $flavors, generateSigningKey: $generateSigningKey, firebaseAuth: $firebaseAuth, useSonar: $useSonar, graphql: $graphql, screenUtil: $screenUtil, router: $router, localization: $localization, theming: $theming, signingVars: $signingVars, screens: $screens, styles: $styles, swaggerUrl: $swaggerUrl)'; + return 'Config(branch: $branch, localVersion: $localVersion, remoteVersion: $remoteVersion, projectPath: $projectPath, projectName: $projectName, projectExists: $projectExists, organization: $organization, platformsList: $platformsList, stateManager: $stateManager, flavorize: $flavorize, flavors: $flavors, generateSigningKey: $generateSigningKey, firebaseAuth: $firebaseAuth, useSonar: $useSonar, graphql: $graphql, screenUtil: $screenUtil, router: $router, localization: $localization, theming: $theming, signingVars: $signingVars, screens: $screens, styles: $styles, swaggerUrl: $swaggerUrl, sentry: $sentry)'; } @override @@ -530,6 +564,8 @@ class _$ConfigImpl extends _Config { other.organization == organization) && (identical(other.platformsList, platformsList) || other.platformsList == platformsList) && + (identical(other.stateManager, stateManager) || + other.stateManager == stateManager) && (identical(other.flavorize, flavorize) || other.flavorize == flavorize) && (identical(other.flavors, flavors) || other.flavors == flavors) && @@ -551,7 +587,8 @@ class _$ConfigImpl extends _Config { const DeepCollectionEquality().equals(other._screens, _screens) && const DeepCollectionEquality().equals(other._styles, _styles) && (identical(other.swaggerUrl, swaggerUrl) || - other.swaggerUrl == swaggerUrl)); + other.swaggerUrl == swaggerUrl) && + (identical(other.sentry, sentry) || other.sentry == sentry)); } @JsonKey(ignore: true) @@ -566,6 +603,7 @@ class _$ConfigImpl extends _Config { projectExists, organization, platformsList, + stateManager, flavorize, flavors, generateSigningKey, @@ -579,7 +617,8 @@ class _$ConfigImpl extends _Config { const DeepCollectionEquality().hash(_signingVars), const DeepCollectionEquality().hash(_screens), const DeepCollectionEquality().hash(_styles), - swaggerUrl + swaggerUrl, + sentry ]); @JsonKey(ignore: true) @@ -606,6 +645,7 @@ abstract class _Config extends Config { final bool projectExists, final String organization, final PlatformsList platformsList, + final ProjectStateManager stateManager, final bool flavorize, final String flavors, final bool generateSigningKey, @@ -620,7 +660,8 @@ abstract class _Config extends Config { final Set screens, @JsonKey(includeFromJson: false, includeToJson: false) final List styles, - final String swaggerUrl}) = _$ConfigImpl; + final String swaggerUrl, + final bool sentry}) = _$ConfigImpl; const _Config._() : super._(); factory _Config.fromJson(Map json) = _$ConfigImpl.fromJson; @@ -642,6 +683,8 @@ abstract class _Config extends Config { @override PlatformsList get platformsList; @override + ProjectStateManager get stateManager; + @override bool get flavorize; @override String get flavors; @@ -671,6 +714,8 @@ abstract class _Config extends Config { @override String get swaggerUrl; @override + bool get sentry; + @override @JsonKey(ignore: true) _$$ConfigImplCopyWith<_$ConfigImpl> get copyWith => throw _privateConstructorUsedError; diff --git a/lib/domain/entity/config/config.g.dart b/lib/domain/entity/config/config.g.dart index aad45acc..e5340daa 100644 --- a/lib/domain/entity/config/config.g.dart +++ b/lib/domain/entity/config/config.g.dart @@ -18,6 +18,9 @@ _$ConfigImpl _$$ConfigImplFromJson(Map json) => _$ConfigImpl( ? const PlatformsList() : PlatformsList.fromJson( json['platformsList'] as Map), + stateManager: $enumDecodeNullable( + _$ProjectStateManagerEnumMap, json['stateManager']) ?? + ProjectStateManager.bloc, flavorize: json['flavorize'] as bool? ?? false, flavors: json['flavors'] as String? ?? '', generateSigningKey: json['generateSigningKey'] as bool? ?? false, @@ -41,6 +44,7 @@ _$ConfigImpl _$$ConfigImplFromJson(Map json) => _$ConfigImpl( .toSet() ?? const {}, swaggerUrl: json['swaggerUrl'] as String? ?? '', + sentry: json['sentry'] as bool? ?? false, ); Map _$$ConfigImplToJson(_$ConfigImpl instance) => @@ -53,6 +57,7 @@ Map _$$ConfigImplToJson(_$ConfigImpl instance) => 'projectExists': instance.projectExists, 'organization': instance.organization, 'platformsList': instance.platformsList, + 'stateManager': _$ProjectStateManagerEnumMap[instance.stateManager]!, 'flavorize': instance.flavorize, 'flavors': instance.flavors, 'generateSigningKey': instance.generateSigningKey, @@ -66,8 +71,16 @@ Map _$$ConfigImplToJson(_$ConfigImpl instance) => 'signingVars': instance.signingVars, 'screens': instance.screens.toList(), 'swaggerUrl': instance.swaggerUrl, + 'sentry': instance.sentry, }; +const _$ProjectStateManagerEnumMap = { + ProjectStateManager.bloc: 'bloc', + ProjectStateManager.provider: 'provider', + ProjectStateManager.riverpod: 'riverpod', + ProjectStateManager.base: 'base', +}; + const _$ProjectRouterEnumMap = { ProjectRouter.goRouter: 'goRouter', ProjectRouter.autoRouter: 'autoRouter', diff --git a/lib/domain/entity/failure/signing_failure.dart b/lib/domain/entity/failure/signing_failure.dart index 1f864000..ad27db6c 100644 --- a/lib/domain/entity/failure/signing_failure.dart +++ b/lib/domain/entity/failure/signing_failure.dart @@ -1,4 +1,4 @@ -import 'package:onix_flutter_bricks/core/arch/domain/entity/failure/failure.dart'; +import 'package:onix_flutter_core_models/onix_flutter_core_models.dart'; enum SigningFailureType { invalidParams, exception, signingAlreadyExist } diff --git a/lib/domain/entity/failure/swagger_parser_failure.dart b/lib/domain/entity/failure/swagger_parser_failure.dart new file mode 100644 index 00000000..f060783e --- /dev/null +++ b/lib/domain/entity/failure/swagger_parser_failure.dart @@ -0,0 +1,6 @@ +import 'package:onix_flutter_core_models/onix_flutter_core_models.dart'; + +// When Failed to parse swagger components +class SwaggerParserFailure implements Failure { + const SwaggerParserFailure(); +} diff --git a/lib/domain/entity/platforms_list/platforms_list.dart b/lib/domain/entity/platforms_list/platforms_list.dart index 4b52005e..76af6bf8 100644 --- a/lib/domain/entity/platforms_list/platforms_list.dart +++ b/lib/domain/entity/platforms_list/platforms_list.dart @@ -23,7 +23,7 @@ class PlatformsList with _$PlatformsList { bool get mobile => android || ios; List asList() { - List platforms = []; + final platforms = []; if (android) platforms.add('android'); if (ios) platforms.add('ios'); @@ -35,11 +35,12 @@ class PlatformsList with _$PlatformsList { } List asPlatformCommandsList() { - List commands = []; + final commands = []; if (android) { - commands.add('apk'); - commands.add('appbundle'); + commands + ..add('apk') + ..add('appbundle'); } if (ios) commands.add('ios'); if (web) commands.add('web'); diff --git a/lib/domain/entity/screen/screen.dart b/lib/domain/entity/screen/screen.dart index f882685f..c277039a 100644 --- a/lib/domain/entity/screen/screen.dart +++ b/lib/domain/entity/screen/screen.dart @@ -1,27 +1,30 @@ import 'package:json_annotation/json_annotation.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; part 'screen.g.dart'; @JsonSerializable() class Screen { String name; - ScreenStateManager stateManager; + @JsonKey(includeFromJson: false, includeToJson: false) + StateManagementVariant stateVariant; bool exists; bool initial; Screen({ required this.name, - this.stateManager = ScreenStateManager.none, + this.stateVariant = const StatelessStateManagementVariant(), this.exists = false, this.initial = false, }); Screen.copyOf(Screen screen) : this( - name: screen.name, - stateManager: screen.stateManager, - exists: screen.exists, - initial: screen.initial); + name: screen.name, + stateVariant: screen.stateVariant, + exists: screen.exists, + initial: screen.initial, + ); @override bool operator ==(Object other) => @@ -29,7 +32,7 @@ class Screen { other is Screen && runtimeType == other.runtimeType && name == other.name && - stateManager == other.stateManager && + stateVariant == other.stateVariant && exists == other.exists && initial == other.initial; @@ -38,12 +41,10 @@ class Screen { @override String toString() { - return 'ScreenEntity{name: $name, bloc: $stateManager, exists: $exists, initial: $initial}'; + return 'ScreenEntity{name: $name, stateManager: ${stateVariant.name}, exists: $exists, initial: $initial}'; } Map toJson() => _$ScreenToJson(this); factory Screen.fromJson(Map json) => _$ScreenFromJson(json); } - -enum ScreenStateManager { bloc, cubit, none } diff --git a/lib/domain/entity/screen/screen.g.dart b/lib/domain/entity/screen/screen.g.dart index 240c1d6e..5dfa0cfe 100644 --- a/lib/domain/entity/screen/screen.g.dart +++ b/lib/domain/entity/screen/screen.g.dart @@ -8,22 +8,12 @@ part of 'screen.dart'; Screen _$ScreenFromJson(Map json) => Screen( name: json['name'] as String, - stateManager: $enumDecodeNullable( - _$ScreenStateManagerEnumMap, json['stateManager']) ?? - ScreenStateManager.none, exists: json['exists'] as bool? ?? false, initial: json['initial'] as bool? ?? false, ); Map _$ScreenToJson(Screen instance) => { 'name': instance.name, - 'stateManager': _$ScreenStateManagerEnumMap[instance.stateManager]!, 'exists': instance.exists, 'initial': instance.initial, }; - -const _$ScreenStateManagerEnumMap = { - ScreenStateManager.bloc: 'bloc', - ScreenStateManager.cubit: 'cubit', - ScreenStateManager.none: 'none', -}; diff --git a/lib/domain/entity/state_management/project_state_manager.dart b/lib/domain/entity/state_management/project_state_manager.dart new file mode 100644 index 00000000..118689af --- /dev/null +++ b/lib/domain/entity/state_management/project_state_manager.dart @@ -0,0 +1,34 @@ +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/default_screen_route_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/strategy/state_manager_strategy.dart'; +import 'package:onix_flutter_bricks/domain/service/strategy/strategies/base_strategy.dart'; +import 'package:onix_flutter_bricks/domain/service/strategy/strategies/bloc_strategy.dart'; +import 'package:onix_flutter_bricks/domain/service/strategy/strategies/provider_strategy.dart'; +import 'package:onix_flutter_bricks/domain/service/strategy/strategies/riverpod_strategy.dart'; + +enum ProjectStateManager { + bloc, + provider, + riverpod, + base; + + StateManagerStrategy get strategy { + switch (this) { + case ProjectStateManager.bloc: + return BlocStateManagerStrategy( + defaultScreenRouteGenerator: DefaultScreenRouteGenerator(), + ); + case ProjectStateManager.base: + return BaseStrategy( + defaultScreenRouteGenerator: DefaultScreenRouteGenerator(), + ); + case ProjectStateManager.provider: + return ProviderStrategy( + defaultScreenRouteGenerator: DefaultScreenRouteGenerator(), + ); + case ProjectStateManager.riverpod: + return RiverpodStrategy( + defaultScreenRouteGenerator: DefaultScreenRouteGenerator(), + ); + } + } +} diff --git a/lib/domain/entity/state_management/state_management_variant.dart b/lib/domain/entity/state_management/state_management_variant.dart new file mode 100644 index 00000000..273e6ddc --- /dev/null +++ b/lib/domain/entity/state_management/state_management_variant.dart @@ -0,0 +1,98 @@ +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/bloc_screen_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/cubit_screen_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/provider_screen_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/riverpod_stateful_screen_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/riverpod_stateless_screen_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/stateful_screen_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/stateless_screen_generator.dart'; + +abstract class StateManagementVariant { + String get name; + + ScreenGenerationService get screenGenerator; + + const StateManagementVariant(); + + @override + bool operator ==(Object other) { + return runtimeType == other.runtimeType; + } + + @override + int get hashCode => runtimeType.hashCode; +} + +final class StatelessStateManagementVariant extends StateManagementVariant { + @override + String get name => 'Stateless'; + + @override + ScreenGenerationService get screenGenerator => StatelessScreenGenerator(); + + const StatelessStateManagementVariant(); +} + +final class StatefulStateManagementVariant extends StateManagementVariant { + @override + String get name => 'Stateful'; + + @override + ScreenGenerationService get screenGenerator => StatefulScreenGenerator(); + + const StatefulStateManagementVariant(); +} + +final class BlocStateManagementVariant extends StateManagementVariant { + @override + String get name => 'Bloc'; + + @override + ScreenGenerationService get screenGenerator => BlocScreenGenerator(); + + const BlocStateManagementVariant(); +} + +final class CubitStateManagementVariant extends StateManagementVariant { + @override + String get name => 'Cubit'; + + @override + ScreenGenerationService get screenGenerator => CubitScreenGenerator(); + + const CubitStateManagementVariant(); +} + +final class ProviderStateManagementVariant extends StateManagementVariant { + @override + String get name => 'Provider'; + + @override + ScreenGenerationService get screenGenerator => ProviderScreenGenerator(); + + const ProviderStateManagementVariant(); +} + +final class RiverpodStatelessStateManagementVariant + extends StateManagementVariant { + @override + String get name => 'RiverpodStateless'; + + @override + ScreenGenerationService get screenGenerator => + RiverpodStatelessScreenGenerator(); + + const RiverpodStatelessStateManagementVariant(); +} + +final class RiverpodStatefulStateManagementVariant + extends StateManagementVariant { + @override + String get name => 'RiverpodStateful'; + + @override + ScreenGenerationService get screenGenerator => + RiverpodStatefulScreenGenerator(); + + const RiverpodStatefulStateManagementVariant(); +} diff --git a/lib/domain/repository/screen_repository.dart b/lib/domain/repository/screen_repository.dart index 8a9463af..cc978c5e 100644 --- a/lib/domain/repository/screen_repository.dart +++ b/lib/domain/repository/screen_repository.dart @@ -1,6 +1,6 @@ import 'package:onix_flutter_bricks/domain/entity/screen/screen.dart'; -abstract class ScreenRepository { +abstract interface class ScreenRepository { Set get screens; bool exists({required String screenName}); diff --git a/lib/domain/repository/swagger_repository.dart b/lib/domain/repository/swagger_repository.dart index 22418dec..01390614 100644 --- a/lib/domain/repository/swagger_repository.dart +++ b/lib/domain/repository/swagger_repository.dart @@ -1,7 +1,7 @@ -import 'package:onix_flutter_bricks/core/arch/domain/entity/result/result.dart'; import 'package:onix_flutter_bricks/domain/entity/component/components.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; -abstract class SwaggerRepository { +abstract interface class SwaggerRepository { Components? components; Future> fetchSwaggerData({ diff --git a/lib/domain/service/base/base_generation_service.dart b/lib/domain/service/base/base_generation_service.dart index 024f5cc8..60f604aa 100644 --- a/lib/domain/service/base/base_generation_service.dart +++ b/lib/domain/service/base/base_generation_service.dart @@ -1,5 +1,13 @@ import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; -abstract interface class BaseGenerationService { - Future generate(BaseGenerationParams params); +// ignore: one_member_abstracts +abstract class BaseGenerationService { + Future generate(T params); +} + +abstract class ScreenGenerationService + extends BaseGenerationService { + @override + Future generate(ScreenGeneratorParams params); } diff --git a/lib/domain/service/base/class_builder/freezed_class_builder.dart b/lib/domain/service/base/class_builder/freezed_class_builder.dart index 2a9b78cd..5185c1e9 100644 --- a/lib/domain/service/base/class_builder/freezed_class_builder.dart +++ b/lib/domain/service/base/class_builder/freezed_class_builder.dart @@ -2,6 +2,7 @@ import 'package:onix_flutter_bricks/domain/service/base/class_builder/class_buil import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; import 'package:recase/recase.dart'; +// ignore_for_file: avoid_setters_without_getters class FreezedClassBuilder extends ClassBuilder { final String _className; final String _classNameSuffix; @@ -31,31 +32,35 @@ class FreezedClassBuilder extends ClassBuilder { final classPartImport = '${_className.snakeCase}$importSuffix'; final classFullName = '${_className.pascalCase}${_classNameSuffix.pascalCase}'; - lines.add('import \'package:freezed_annotation/freezed_annotation.dart\';'); - lines.addAll(_imports); - lines.addNewLine(); - lines.add('part \'$classPartImport.freezed.dart\';'); - lines.addNewLine(); - lines.add('@freezed'); - lines.add('class $classFullName with _\$$classFullName {'); + lines + ..add("import 'package:freezed_annotation/freezed_annotation.dart';") + ..addAll(_imports) + ..addNewLine() + ..add("part '$classPartImport.freezed.dart';") + ..addNewLine() + ..add('@freezed') + ..add('class $classFullName with _\$$classFullName {'); if (_baseConstructorProperties.isEmpty) { - lines.add('factory $classFullName() = _$classFullName;'); + lines.add('const factory $classFullName() = _$classFullName;'); } else { - lines.add('factory $classFullName({'); - lines.addAll(_baseConstructorProperties); - lines.add('}) = _$classFullName;'); + lines + ..add('factory $classFullName({') + ..addAll(_baseConstructorProperties) + ..add('}) = _$classFullName;'); } lines.addNewLine(); if (_emptyConstructorProperties.isNotEmpty) { - lines.add('factory $classFullName.empty() => $classFullName('); - lines.addAll(_emptyConstructorProperties); - lines.add(');'); + lines + ..add('factory $classFullName.empty() => $classFullName(') + ..addAll(_emptyConstructorProperties) + ..add(');'); } else { - lines.add('factory $classFullName.empty() => $classFullName();'); + lines.add('factory $classFullName.empty() => const $classFullName();'); } - lines.addNewLine(); - lines.add('}'); - lines.addNewLine(); + lines + ..addNewLine() + ..add('}') + ..addNewLine(); return super.build(); } } diff --git a/lib/domain/service/base/class_builder/json_class_builder.dart b/lib/domain/service/base/class_builder/json_class_builder.dart index d3072261..fe68b2f6 100644 --- a/lib/domain/service/base/class_builder/json_class_builder.dart +++ b/lib/domain/service/base/class_builder/json_class_builder.dart @@ -3,6 +3,7 @@ import 'package:onix_flutter_bricks/domain/service/base/class_builder/class_buil import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; import 'package:recase/recase.dart'; +// ignore_for_file: avoid_setters_without_getters class JsonClassBuilder extends ClassBuilder { final String _className; final String _classNameSuffix; @@ -37,53 +38,62 @@ class JsonClassBuilder extends ClassBuilder { final classPartImport = '${_className.snakeCase}$importSuffix'; final classFullName = '${_className.pascalCase}${_classNameSuffix.pascalCase}'; - lines.add('import \'package:json_annotation/json_annotation.dart\';'); - lines.addAll(_imports); - lines.addNewLine(); - lines.add('part \'$classPartImport.g.dart\';'); - lines.addNewLine(); - lines.add('@JsonSerializable()'); - lines.add('class $classFullName {'); - lines.addNewLine(); - lines.addAll(_variableDeclarations); - lines.addNewLine(); - if(_variableDeclarations.isEmpty) { + lines + ..add("import 'package:json_annotation/json_annotation.dart';") + ..addAll(_imports) + ..addNewLine() + ..add("part '$classPartImport.g.dart';") + ..addNewLine() + ..add('@JsonSerializable()') + ..add('class $classFullName {') + ..addNewLine() + ..addAll(_variableDeclarations) + ..addNewLine(); + if (_variableDeclarations.isEmpty) { lines.add('const $classFullName();'); } else { - lines.add('const $classFullName({'); - lines.addAll(_baseConstructorProperties); - lines.add('});'); + lines + ..add('const $classFullName({') + ..addAll(_baseConstructorProperties) + ..add('});'); } - lines.addNewLine(); - lines.add( - 'factory $classFullName.fromJson(Map json) => _\$${classFullName}FromJson(json);'); + lines + ..addNewLine() + ..add( + 'factory $classFullName.fromJson(Map json,) ' + '=> _\$${classFullName}FromJson(json);', + ); if (_withToJson) { - lines.addNewLine(); - lines.add( - 'Map toJson() => _\$${classFullName}ToJson(this);'); + lines + ..addNewLine() + ..add( + 'Map toJson() => _\$${classFullName}ToJson(this);', + ); } - lines.add('}'); - lines.addNewLine(); + lines + ..add('}') + ..addNewLine(); return super.build(); } static Iterable variablesFromJsonVariable( - Iterable input) { + Iterable input, + ) { return input.map( (e) { - final variableDeclaration = List.empty(growable: true); - variableDeclaration.add('@JsonKey(includeIfNull: false)'); - variableDeclaration.addNewLine(); - variableDeclaration - .add('final ${e.dartType}${e.nullable ? '?' : ''} ${e.name};'); + final variableDeclaration = List.empty(growable: true) + ..add('@JsonKey(includeIfNull: false)') + ..addNewLine() + ..add('final ${e.dartType}${e.nullable ? '?' : ''} ${e.name};'); return variableDeclaration.join('\n'); }, ); } static Iterable constructorPropertiesFromJsonVariable( - Iterable input) { + Iterable input, + ) { return input.map( (e) { final prefix = e.nullable ? '' : 'required'; diff --git a/lib/domain/service/component_generator/component_generator_service.dart b/lib/domain/service/component_generator/component_generator_service.dart index b5411f6e..a4696b95 100644 --- a/lib/domain/service/component_generator/component_generator_service.dart +++ b/lib/domain/service/component_generator/component_generator_service.dart @@ -1,29 +1,27 @@ import 'dart:io'; import 'package:collection/collection.dart'; +import 'package:onix_flutter_bricks/app/extension/logger_extension.dart'; import 'package:onix_flutter_bricks/app/swagger_const.dart'; import 'package:onix_flutter_bricks/app/util/enum/data_file_type.dart'; import 'package:onix_flutter_bricks/app/util/extenstion/data_components_extension.dart'; import 'package:onix_flutter_bricks/app/util/extenstion/swagger_type_extension.dart'; import 'package:onix_flutter_bricks/core/di/app.dart'; -import 'package:onix_flutter_bricks/core/extension/logger_extension.dart'; import 'package:onix_flutter_bricks/domain/entity/component/data_object_component.dart'; import 'package:onix_flutter_bricks/domain/entity/component/data_object_reference.dart'; import 'package:onix_flutter_bricks/domain/entity/component/enum_param_component.dart'; import 'package:onix_flutter_bricks/domain/entity/component/request_component.dart'; import 'package:onix_flutter_bricks/domain/entity/component/source_component.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/component_generator/params/component_generator_params.dart'; import 'package:recase/recase.dart'; -class ComponentGeneratorService implements BaseGenerationService { - @override - Future generate(BaseGenerationParams params) async { - if (params is! ComponentGeneratorParams) { - return 'Incorrect params'; - } +class ComponentGeneratorService + implements BaseGenerationService { + const ComponentGeneratorService(); + @override + Future generate(ComponentGeneratorParams params) async { try { final projectLibFolder = '${params.projectPath}/${params.projectName}/lib'; @@ -88,7 +86,7 @@ class ComponentGeneratorService implements BaseGenerationService { final declarationFilePath = sourceComponent.getDeclarationFilePath(projectLibFolder); - final declarationBody = sourceComponent.getDeclarationBody(projectName); + final declarationBody = sourceComponent.getSourceDeclarationBody(projectName); await _createFile(filePath: declarationFilePath, fileBody: declarationBody); ///Create Implementation @@ -96,9 +94,11 @@ class ComponentGeneratorService implements BaseGenerationService { sourceComponent.getImplementationFilePath(projectLibFolder); final implementationBody = - sourceComponent.getImplementationBody(projectName); + sourceComponent.getSourceImplementationBody(projectName); await _createFile( - filePath: implementationFilePath, fileBody: implementationBody); + filePath: implementationFilePath, + fileBody: implementationBody, + ); ///Create SL declarations final sourceSLPath = '$projectLibFolder/core/di/source.dart'; @@ -106,21 +106,24 @@ class ComponentGeneratorService implements BaseGenerationService { final slContent = await sourceSlFile.readAsString(); ///SL Imports - final importLines = List.empty(growable: true); - importLines.add(sourceComponent.getDeclarationImport(projectName)); - importLines.add(sourceComponent.getImplementationImport(projectName)); - importLines.add(SwaggerConst.swaggerSLImportsKey); + final importLines = List.empty(growable: true) + ..add(sourceComponent.getDeclarationImport(projectName)) + ..add(sourceComponent.getImplementationImport(projectName)) + ..add(SwaggerConst.swaggerSLImportsKey); ///SL Code final className = sourceComponent.name.pascalCase; - final codeLines = List.empty(growable: true); - codeLines.add( - 'getIt.registerSingleton<${className}Source>(${className}SourceImpl('); - codeLines.add( - 'getIt.get(instanceName: DioConst.defaultApiClientName),'); - codeLines.add('getIt.get(),'); - codeLines.add('),);'); - codeLines.add(SwaggerConst.swaggerSourceSLDeclarationKey); + final codeLines = List.empty(growable: true) + ..add( + 'getIt.registerSingleton<${className}Source>(${className}SourceImpl(', + ) + ..add( + 'getIt.get(instanceName: DioConst.defaultApiClientName),', + ) + ..add('getIt.get(),') + ..add('),);') + ..add(SwaggerConst.swaggerSourceSLDeclarationKey); + final imports = importLines.join('\n'); final code = codeLines.join('\n'); await sourceSlFile.writeAsString( @@ -142,7 +145,9 @@ class ComponentGeneratorService implements BaseGenerationService { final repoDeclarationBody = sourceComponent.getRepoDeclarationBody(projectName); await _createFile( - filePath: repoDeclarationFilePath, fileBody: repoDeclarationBody); + filePath: repoDeclarationFilePath, + fileBody: repoDeclarationBody, + ); ///Create repo implementation final repoImplFolder = sourceComponent.getRepositoryImplFolderPath( @@ -162,21 +167,20 @@ class ComponentGeneratorService implements BaseGenerationService { final repoSlContent = await repoSlFile.readAsString(); ///SL Imports - final repoImportLines = List.empty(growable: true); - repoImportLines.add(sourceComponent.getDeclarationImport(projectName)); - repoImportLines.add(sourceComponent.getRepoDeclarationImport(projectName)); - repoImportLines - .add(sourceComponent.getRepoImplementationImport(projectName)); - repoImportLines.add(SwaggerConst.swaggerSLImportsKey); + final repoImportLines = List.empty(growable: true) + ..add(sourceComponent.getDeclarationImport(projectName)) + ..add(sourceComponent.getRepoDeclarationImport(projectName)) + ..add(sourceComponent.getRepoImplementationImport(projectName)) + ..add(SwaggerConst.swaggerSLImportsKey); final repoClassName = sourceComponent.name.pascalCase; - final repoSLCodeLines = List.empty(growable: true); - repoSLCodeLines - .add('getIt.registerLazySingleton<${repoClassName}Repository>('); - repoSLCodeLines.add( - '() => ${repoClassName}RepositoryImpl(getIt<${repoClassName}Source>()),'); - repoSLCodeLines.add(');'); - repoSLCodeLines.add(SwaggerConst.swaggerRepoSLDeclarationKey); + final repoSLCodeLines = List.empty(growable: true) + ..add('getIt.registerLazySingleton<${repoClassName}Repository>(') + ..add( + '() => ${repoClassName}RepositoryImpl(getIt<${repoClassName}Source>(),),', + ) + ..add(');') + ..add(SwaggerConst.swaggerRepoSLDeclarationKey); final repoSLImports = repoImportLines.join('\n'); final repoSLCode = repoSLCodeLines.join('\n'); await repoSlFile.writeAsString( @@ -196,7 +200,7 @@ class ComponentGeneratorService implements BaseGenerationService { final addedDataComponents = List.empty(growable: true); ///go through each reference and create object - for (var e in references) { + for (final e in references) { final dataObject = components.firstWhereOrNull( (component) => component.name == e.fileReference.reference, ); @@ -252,7 +256,7 @@ class ComponentGeneratorService implements BaseGenerationService { String projectName, List addedDataComponents, ) async { - for (var e in addedDataComponents) { + for (final e in addedDataComponents) { ///Create Entities final entityRawFolder = e.getFileFolder(DataFileType.entity); @@ -271,7 +275,7 @@ class ComponentGeneratorService implements BaseGenerationService { await _createFile(filePath: entityPath, fileBody: entityBody); } - for (var e in addedDataComponents) { + for (final e in addedDataComponents) { ///Create mappers final mapperRawFolder = e.getObjectMapperFolder(); final mapperRawPath = e.getObjectMapperFilePath(); @@ -284,8 +288,8 @@ class ComponentGeneratorService implements BaseGenerationService { e.fileReference.getFileImportName(DataFileType.response); final requestFilePath = '$projectLibFolder/$requestRawFilePath'; final responseFilePath = '$projectLibFolder/$responseRawFilePath'; - final isRequestFileExist = await File(requestFilePath).exists(); - final isResponseFileExist = await File(responseFilePath).exists(); + final isRequestFileExist = File(requestFilePath).existsSync(); + final isResponseFileExist = File(responseFilePath).existsSync(); if (isRequestFileExist || isResponseFileExist) { final mapperBody = e.getMapperBody( projectName: projectName, @@ -304,9 +308,9 @@ class ComponentGeneratorService implements BaseGenerationService { List enums, List components, ) async { - final enumsCopy = List.from(enums, growable: true); - for (var component in components) { - for (var variable in component.variables) { + final enumsCopy = List.of(enums); + for (final component in components) { + for (final variable in component.variables) { final innerEnum = variable.type.getSwaggerEnumReference(); if (innerEnum != null) { enumsCopy.add( @@ -319,7 +323,7 @@ class ComponentGeneratorService implements BaseGenerationService { } } - for (var e in enumsCopy) { + for (final e in enumsCopy) { final folderPath = e.getFolderPath(projectLibFolder); await _createFolders(folderPath, '_createEnums'); final filePath = e.getFilePath(projectLibFolder); @@ -335,7 +339,7 @@ class ComponentGeneratorService implements BaseGenerationService { List requests, ) async { final enumsCopy = List.empty(growable: true); - for (var e in requests) { + for (final e in requests) { ///Check request if (e.requestBody != null) { final enumRef = e.requestBody!.type.getSwaggerEnumReference(); @@ -361,7 +365,7 @@ class ComponentGeneratorService implements BaseGenerationService { } ///Check query params - for (var qParam in e.queryParams) { + for (final qParam in e.queryParams) { final enumRef = qParam.type.getSwaggerEnumReference(); if (enumRef != null) { enumsCopy.add( @@ -374,7 +378,7 @@ class ComponentGeneratorService implements BaseGenerationService { } ///Check path params - for (var pParam in e.pathParams) { + for (final pParam in e.pathParams) { final enumRef = pParam.type.getSwaggerEnumReference(); if (enumRef != null) { enumsCopy.add( @@ -387,7 +391,7 @@ class ComponentGeneratorService implements BaseGenerationService { } } - for (var e in enumsCopy) { + for (final e in enumsCopy) { final folderPath = e.getFolderPath(projectLibFolder); await _createFolders(folderPath, '_createRequestEnums'); final filePath = e.getFilePath(projectLibFolder); @@ -403,7 +407,7 @@ class ComponentGeneratorService implements BaseGenerationService { DataObjectComponent dataObject, ) { final innerReferences = List.empty(growable: true); - for (var e in dataObject.variables) { + for (final e in dataObject.variables) { final ref = e.type.getSwaggerObjectReference(); if (ref != null) { innerReferences.add( @@ -420,7 +424,7 @@ class ComponentGeneratorService implements BaseGenerationService { }) async { final file = File(filePath); try { - final isAlreadyExist = await file.exists(); + final isAlreadyExist = file.existsSync(); if (isAlreadyExist) { logger.i('File already exists: $filePath'); return false; @@ -441,7 +445,7 @@ class ComponentGeneratorService implements BaseGenerationService { ) async { try { final directory = Directory(path); - if (await directory.exists()) { + if (directory.existsSync()) { logger.i('$methodCaller. Directory already exists: $path'); } else { await directory.create(recursive: true); diff --git a/lib/domain/service/docs_service/docs_service.dart b/lib/domain/service/docs_service/docs_service.dart index f5244045..2a3c10f5 100644 --- a/lib/domain/service/docs_service/docs_service.dart +++ b/lib/domain/service/docs_service/docs_service.dart @@ -3,14 +3,14 @@ import 'dart:io'; import 'package:flutter/services.dart' show rootBundle; import 'package:onix_flutter_bricks/core/di/app.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/docs_service/enum/document_type.dart'; import 'package:onix_flutter_bricks/domain/service/docs_service/params/docs_generation_params.dart'; import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; import 'package:onix_flutter_bricks/util/extension/flavor_extension.dart'; import 'package:recase/recase.dart'; -class DocsService implements BaseGenerationService { +class DocsService + implements BaseGenerationService { final flavorsTitle = '* **Flavor** - type of application configuration. Flavored 2 supports following flavors:'; final _appNamePattern = '{app_name}'; @@ -25,10 +25,7 @@ class DocsService implements BaseGenerationService { final _flavorizrInstructions = '{flavorizr_instructions}'; @override - Future generate(BaseGenerationParams params) async { - if (params is! DocsGenerationParams) { - return 'Incorrect params'; - } + Future generate(DocsGenerationParams params) async { try { final projectPath = '${params.projectPath}/${params.projectName}'; //remove existing readme.md diff --git a/lib/domain/service/fastlane_service/fastlane_service.dart b/lib/domain/service/fastlane_service/fastlane_service.dart index 36c30d9a..11a18ff1 100644 --- a/lib/domain/service/fastlane_service/fastlane_service.dart +++ b/lib/domain/service/fastlane_service/fastlane_service.dart @@ -3,7 +3,6 @@ import 'dart:io'; import 'package:flutter/services.dart'; import 'package:onix_flutter_bricks/core/di/app.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/fastlane_service/enums/fastlane_assets.dart'; import 'package:onix_flutter_bricks/domain/service/fastlane_service/enums/fastlane_env_vars.dart'; import 'package:onix_flutter_bricks/domain/service/fastlane_service/params/fastlane_generation_params.dart'; @@ -18,13 +17,12 @@ const _ios = 'ios'; const _androidFastlane = '/android/fastlane/'; const _iosFastlane = '/ios/fastlane/'; -class FastlaneService implements BaseGenerationService { +class FastlaneService + implements BaseGenerationService { const FastlaneService(); @override - Future generate(BaseGenerationParams params) async { - if (params is! FastlaneGenerationParams) return 'Incorrect params'; - + Future generate(FastlaneGenerationParams params) async { final platforms = params.platforms .where((element) => element == _android || element == _ios); diff --git a/lib/domain/service/fastlane_service/utils/fastlane_makefile_util.dart b/lib/domain/service/fastlane_service/utils/fastlane_makefile_util.dart index 3fda938d..2f756591 100644 --- a/lib/domain/service/fastlane_service/utils/fastlane_makefile_util.dart +++ b/lib/domain/service/fastlane_service/utils/fastlane_makefile_util.dart @@ -1,4 +1,4 @@ -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; typedef FastlaneMakefileParams = void Function( String flavor, diff --git a/lib/domain/service/file_generator_service/file_generator_service.dart b/lib/domain/service/file_generator_service/file_generator_service.dart index 74c71d04..f909e749 100644 --- a/lib/domain/service/file_generator_service/file_generator_service.dart +++ b/lib/domain/service/file_generator_service/file_generator_service.dart @@ -1,25 +1,25 @@ import 'dart:io'; -import 'package:onix_flutter_bricks/core/arch/domain/entity/result/result.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/default_screen_route_generator.dart'; -import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/screen_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/default_screen_route_generator_params.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/signing_generator/params/signing_generator_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/signing_generator/signing_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/styles_generator_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/styles_generator.dart'; import 'package:onix_flutter_bricks/domain/service/output_service/output_service.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; import 'package:recase/recase.dart'; class FileGeneratorService { final OutputService _outputService; - final BaseGenerationService _screenGenerator = ScreenGenerator(); - - final BaseGenerationService _defaultScreenRouteGenerator = - DefaultScreenRouteGenerator(); - - final BaseGenerationService _stylesGenerator = StylesGenerator(); - late BaseGenerationService> _signingGenerator; + final BaseGenerationService + _defaultScreenRouteGenerator = DefaultScreenRouteGenerator(); + final BaseGenerationService _stylesGenerator = + StylesGenerator(); + late final BaseGenerationService, SingingGeneratorParams> + _signingGenerator; FileGeneratorService( this._outputService, @@ -27,13 +27,12 @@ class FileGeneratorService { _signingGenerator = SigningGenerator(_outputService); } - Future generateScreen(BaseGenerationParams params) => - _screenGenerator.generate(params); - - Future generateDefaultScreenRoute(BaseGenerationParams params) => + Future generateDefaultScreenRoute( + DefaultScreenRouteGeneratorParams params, + ) => _defaultScreenRouteGenerator.generate(params); - Future generateStyles(BaseGenerationParams params) => + Future generateStyles(StylesGeneratorParams params) => _stylesGenerator.generate(params); Future generateEmptySourceComponentFolders({ @@ -52,6 +51,6 @@ class FileGeneratorService { .create(recursive: true); } - Future> generateSigning(BaseGenerationParams params) => + Future> generateSigning(SingingGeneratorParams params) => _signingGenerator.generate(params); } diff --git a/lib/domain/service/file_generator_service/screen_generators/bloc_screen_generator.dart b/lib/domain/service/file_generator_service/screen_generators/bloc_screen_generator.dart new file mode 100644 index 00000000..c02bd893 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/bloc_screen_generator.dart @@ -0,0 +1,120 @@ +import 'dart:io'; + +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/bloc_screen_code_content.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/mixins/bloc_content_mixin.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/mixins/di_content_mixin.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/util/enum/project_router.dart'; + +class BlocScreenGenerator extends ScreenGenerationService + with DIContentMixin, BlocContentMixin { + final _screenCodeContent = BlocScreenCodeContent(); + + @override + Future generate(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + + final screenPath = + '${params.projectPath}/${params.projectName}/lib/presentation/screen/${screenName}_screen'; + await Directory(screenPath).create(recursive: true); + + if (params.screen.stateVariant is! StatelessStateManagementVariant) { + await Directory('$screenPath/bloc').create(recursive: true); + } + + ///Create screen files and BLoC files for a screen + await _createFiles(params, screenPath); + + ///Add screen configuration to Navigation Router file + await _createRoutes(params); + + if (params.screen.stateVariant is! StatelessStateManagementVariant && + params.screen.stateVariant is! StatefulStateManagementVariant) { + ///Add DI configuration for state management + await createScreenDIContent(params: params); + } + return true; + } + + Future _createRoutes(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + if (params.router == ProjectRouter.goRouter) { + final routesFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_route.dart'); + final routesContent = routesFile.readAsStringSync(); + //Generate routes enum for GoRouter + final appRoutesContent = _screenCodeContent.createScreenNavigationGoRoute( + input: routesContent, + screenName: screenName, + isLastDeclaration: params.lastScreenItem, + ); + await routesFile.writeAsString(appRoutesContent); + } + + final routerFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_router.dart'); + final routerContent = routerFile.readAsStringSync(); + + ///Create Navigator screen declarations + final filledRouterContent = + _screenCodeContent.createScreenNavigationContent( + input: routerContent, + screenName: screenName, + projectName: params.projectName, + isInitialScreen: params.screen.initial, + router: params.router, + ); + + await routerFile.writeAsString(filledRouterContent); + } + + Future _createFiles( + ScreenGeneratorParams params, + String screenPath, + ) async { + final screenName = params.normalizedScreenName; + final screenFile = + await File('$screenPath/${screenName}_screen.dart').create(); + + ///Write screen file + final screenContent = _screenCodeContent.createScreen( + isGoRouter: params.router == ProjectRouter.goRouter, + screenName: screenName, + projectName: params.projectName, + ); + await screenFile.writeAsString(screenContent); + + ///Write BLoC imports file + final importsFile = + await File('$screenPath/bloc/${screenName}_screen_imports.dart') + .create(); + final importsContent = createBlocImportsContent( + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await importsFile.writeAsString(importsContent); + + ///Write BLoC models file + final modelsFile = + await File('$screenPath/bloc/${screenName}_screen_models.dart') + .create(); + final modelsContent = createBlocModels( + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await modelsFile.writeAsString(modelsContent); + + ///Write BLoC file + final blocFile = await File( + '$screenPath/bloc/${screenName}_screen_${params.screen.stateVariant.name.toLowerCase()}.dart') + .create(); + final blocFileContent = createBlocContent( + projectName: params.projectName, + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await blocFile.writeAsString(blocFileContent); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/cubit_screen_generator.dart b/lib/domain/service/file_generator_service/screen_generators/cubit_screen_generator.dart new file mode 100644 index 00000000..5ab8fdf8 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/cubit_screen_generator.dart @@ -0,0 +1,120 @@ +import 'dart:io'; + +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/cubit_screen_code_content.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/mixins/bloc_content_mixin.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/mixins/di_content_mixin.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/util/enum/project_router.dart'; + +class CubitScreenGenerator extends ScreenGenerationService + with DIContentMixin, BlocContentMixin { + final _screenCodeContent = CubitScreenCodeContent(); + + @override + Future generate(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + + final screenPath = + '${params.projectPath}/${params.projectName}/lib/presentation/screen/${screenName}_screen'; + await Directory(screenPath).create(recursive: true); + + if (params.screen.stateVariant is! StatelessStateManagementVariant) { + await Directory('$screenPath/bloc').create(recursive: true); + } + + ///Create screen files and BLoC files for a screen + await _createFiles(params, screenPath); + + ///Add screen configuration to Navigation Router file + await _createRoutes(params); + + if (params.screen.stateVariant is! StatelessStateManagementVariant) { + ///Add DI configuration for state management + await createScreenDIContent(params: params); + } + return true; + } + + Future _createRoutes(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + if (params.router == ProjectRouter.goRouter) { + final routesFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_route.dart'); + final routesContent = routesFile.readAsStringSync(); + //Generate routes enum for GoRouter + final appRoutesContent = _screenCodeContent.createScreenNavigationGoRoute( + input: routesContent, + screenName: screenName, + isLastDeclaration: params.lastScreenItem, + ); + await routesFile.writeAsString(appRoutesContent); + } + + final routerFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_router.dart', + ); + final routerContent = routerFile.readAsStringSync(); + + ///Create Navigator screen declarations + final filledRouterContent = + _screenCodeContent.createScreenNavigationContent( + input: routerContent, + screenName: screenName, + projectName: params.projectName, + isInitialScreen: params.screen.initial, + router: params.router, + ); + + await routerFile.writeAsString(filledRouterContent); + } + + Future _createFiles( + ScreenGeneratorParams params, + String screenPath, + ) async { + final screenName = params.normalizedScreenName; + final screenFile = + await File('$screenPath/${screenName}_screen.dart').create(); + + ///Write screen file + final screenContent = _screenCodeContent.createScreen( + isGoRouter: params.router == ProjectRouter.goRouter, + screenName: screenName, + projectName: params.projectName, + ); + await screenFile.writeAsString(screenContent); + + ///Write BLoC imports file + final importsFile = + await File('$screenPath/bloc/${screenName}_screen_imports.dart') + .create(); + final importsContent = createBlocImportsContent( + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await importsFile.writeAsString(importsContent); + + ///Write BLoC models file + final modelsFile = + await File('$screenPath/bloc/${screenName}_screen_models.dart') + .create(); + final modelsContent = createBlocModels( + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await modelsFile.writeAsString(modelsContent); + + ///Write BLoC file + final blocFile = await File( + '$screenPath/bloc/${screenName}_screen_${params.screen.stateVariant.name.toLowerCase()}.dart') + .create(); + final blocFileContent = createBlocContent( + projectName: params.projectName, + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await blocFile.writeAsString(blocFileContent); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/default_screen_route_generator.dart b/lib/domain/service/file_generator_service/screen_generators/default_screen_route_generator.dart index f39568c6..6197e490 100644 --- a/lib/domain/service/file_generator_service/screen_generators/default_screen_route_generator.dart +++ b/lib/domain/service/file_generator_service/screen_generators/default_screen_route_generator.dart @@ -1,17 +1,13 @@ import 'dart:io'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/default_screen_route_generator_params.dart'; import 'package:onix_flutter_bricks/util/enum/project_router.dart'; -class DefaultScreenRouteGenerator implements BaseGenerationService { +class DefaultScreenRouteGenerator + implements BaseGenerationService { @override - Future generate(BaseGenerationParams params) async { - if (params is! DefaultScreenRouteGeneratorParams) { - return false; - } - + Future generate(DefaultScreenRouteGeneratorParams params) async { ///Add default configuration to Navigation Router file await _createDefaultRoute(params); @@ -19,16 +15,19 @@ class DefaultScreenRouteGenerator implements BaseGenerationService { } Future _createDefaultRoute( - DefaultScreenRouteGeneratorParams params) async { + DefaultScreenRouteGeneratorParams params, + ) async { if (params.router == ProjectRouter.goRouter) { final routesFile = File( - '${params.projectPath}/${params.projectName}/lib/app/router/app_route.dart'); - String routesContent = routesFile.readAsStringSync(); + '${params.projectPath}/${params.projectName}/lib/app/router/app_route.dart', + ); + final routesContent = routesFile.readAsStringSync(); //Generate routes enum for GoRouter final appRoutesContent = routesContent.replaceAll( - '//{routes declaration end}', - 'root(\'/\');\n//{routes declaration end}'); - routesFile.writeAsString(appRoutesContent); + '//{routes declaration end}', + "root('/');\n//{routes declaration end}", + ); + await routesFile.writeAsString(appRoutesContent); } } } diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/bloc_screen_code_content.dart b/lib/domain/service/file_generator_service/screen_generators/gen/bloc_screen_code_content.dart new file mode 100644 index 00000000..6575eb7c --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/bloc_screen_code_content.dart @@ -0,0 +1,90 @@ +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart'; +import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; +import 'package:recase/recase.dart'; + +class BlocScreenCodeContent extends ScreenCodeContent { + @override + String createScreen({ + required bool isGoRouter, + required String screenName, + required String projectName, + }) { + final screenClassName = screenName.pascalCase; + final screenClassImport = screenName.snakeCase; + final codeLines = List.empty(growable: true); + final blocClassType = '${screenClassName}ScreenBloc'; + + /// Add imports + codeLines.add("import 'package:flutter/material.dart';"); + if (!isGoRouter) { + codeLines.add("import 'package:auto_route/annotations.dart';"); + } + + codeLines + ..add("import 'package:onix_flutter_bloc/onix_flutter_bloc.dart';") + ..add("import 'package:get_it/get_it.dart';") + ..add( + "import 'package:$projectName/presentation/screen/${screenClassImport}_screen/bloc/${screenClassImport}_screen_imports.dart';", + ) + ..addNewLine(); + + /// Add annotation in AutoRoute navigation used + if (!isGoRouter) { + codeLines.add('@RoutePage()'); + } + + /// Add screen widget code + codeLines + ..add('class ${screenClassName}Screen extends StatefulWidget {') + ..add('const ${screenClassName}Screen({') + ..add('super.key,') + ..add('});') + ..addNewLine() + ..add('@override') + ..add( + 'State<${screenClassName}Screen> createState() => _${screenClassName}ScreenState();', + ) + ..add('}') + ..addNewLine() + + /// Add screen widget state code + ..add('class _${screenClassName}ScreenState') + ..add('extends BaseState<') + ..add('${screenClassName}ScreenState, ') + ..add('$blocClassType, ') + ..add('${screenClassName}ScreenSR, ') + ..add('${screenClassName}Screen> {') + ..add('@override') + ..add( + '$blocClassType createBloc() => GetIt.I.get<$blocClassType>();', + ) + ..addNewLine() + ..add('@override') + ..add('Widget buildWidget(BuildContext context) {') + ..add('return srObserver(') + ..add('context: context,') + ..add('child: Scaffold(') + ..add('body: SizedBox.expand(') + ..add('child: blocConsumer(') + ..add('builder: (state) => const Center(') + ..add("child: Text('$screenClassName screen'),") + ..add('),') + ..add('listener: (context, state) {},') + ..add('),),),') + ..add('onSR: _onSingleResult,') + ..add(' );}') + ..addNewLine() + + /// Add SR callback handler + ..add( + 'void _onSingleResult(BuildContext context, ${screenClassName}ScreenSR singleResult) {', + ) + ..add('singleResult.when(') + ..add('loadFinished: () {') + ..add('},);}') + ..addNewLine() + ..add('}') + ..addNewLine(); + return codeLines.join('\n'); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/cubit_screen_code_content.dart b/lib/domain/service/file_generator_service/screen_generators/gen/cubit_screen_code_content.dart new file mode 100644 index 00000000..6e54304c --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/cubit_screen_code_content.dart @@ -0,0 +1,91 @@ +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart'; +import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; +import 'package:recase/recase.dart'; + +class CubitScreenCodeContent extends ScreenCodeContent { + @override + String createScreen({ + required bool isGoRouter, + required String screenName, + required String projectName, + }) { + final screenClassName = screenName.pascalCase; + final screenClassImport = screenName.snakeCase; + final codeLines = List.empty(growable: true); + final cubitClassType = '${screenClassName}ScreenCubit'; + + /// Add imports + codeLines.add("import 'package:flutter/material.dart';"); + if (!isGoRouter) { + codeLines.add("import 'package:auto_route/annotations.dart';"); + } + + codeLines + ..add("import 'package:onix_flutter_bloc/onix_flutter_bloc.dart';") + ..add("import 'package:get_it/get_it.dart';") + ..add( + "import 'package:$projectName/presentation/screen/${screenClassImport}_screen/bloc/${screenClassImport}_screen_imports.dart';", + ) + ..addNewLine(); + + /// Add annotation in AutoRoute navigation used + if (!isGoRouter) { + codeLines.add('@RoutePage()'); + } + + /// Add screen widget code + codeLines + ..add('class ${screenClassName}Screen extends StatefulWidget {') + ..add('const ${screenClassName}Screen({') + ..add('super.key,') + ..add('});') + ..addNewLine() + ..add('@override') + ..add( + 'State<${screenClassName}Screen> createState() => _${screenClassName}ScreenState();', + ) + ..add('}') + ..addNewLine() + + /// Add screen widget state code + + ..add('class _${screenClassName}ScreenState') + ..add('extends BaseCubitState<') + ..add('${screenClassName}ScreenState, ') + ..add('$cubitClassType, ') + ..add('${screenClassName}ScreenSR, ') + ..add('${screenClassName}Screen> {') + ..add('@override') + ..add( + '$cubitClassType createCubit() => GetIt.I.get<$cubitClassType>();', + ) + ..addNewLine() + ..add('@override') + ..add('Widget buildWidget(BuildContext context) {') + ..add('return srObserver(') + ..add('context: context,') + ..add('child: Scaffold(') + ..add('body: SizedBox.expand(') + ..add('child: blocConsumer(') + ..add('builder: (state) => const Center(') + ..add("child: Text('$screenClassName screen'),") + ..add('),') + ..add('listener: (context, state) {},') + ..add('),),),') + ..add('onSR: _onSingleResult,') + ..add(' );}') + ..addNewLine() + + /// Add SR callback handler + ..add( + 'void _onSingleResult(BuildContext context, ${screenClassName}ScreenSR singleResult) {', + ) + ..add('singleResult.when(') + ..add('loadFinished: () {') + ..add('},);}') + ..addNewLine() + ..add('}') + ..addNewLine(); + return codeLines.join('\n'); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/mixins/bloc_content_mixin.dart b/lib/domain/service/file_generator_service/screen_generators/gen/mixins/bloc_content_mixin.dart new file mode 100644 index 00000000..7e6bf0c7 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/mixins/bloc_content_mixin.dart @@ -0,0 +1,142 @@ +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; +import 'package:recase/recase.dart'; + +mixin BlocContentMixin on ScreenGenerationService { + String createBlocImportsContent({ + required String screenName, + required StateManagementVariant stateManagement, + }) { + final screenClassImport = screenName.snakeCase; + final codeLines = List.empty(growable: true) + ..add( + "export '${screenClassImport}_screen_${stateManagement.name.toLowerCase()}.dart';", + ) + ..add("export '${screenClassImport}_screen_models.dart';") + ..addNewLine(); + return codeLines.join('\n'); + } + + String createBlocContent({ + required String projectName, + required String screenName, + required StateManagementVariant stateManagement, + }) { + ///Declare BLoC classes names + final stateManagementSuffix = stateManagement.name; + final screenClassImport = screenName.snakeCase; + final className = '${screenName.pascalCase}Screen$stateManagementSuffix'; + final eventName = stateManagement == const BlocStateManagementVariant() + ? '${screenName.pascalCase}ScreenEvent, ' + : ''; + final stateName = '${screenName.pascalCase}ScreenState'; + final srName = '${screenName.pascalCase}ScreenSR'; + final initFunctionName = + stateManagement == const BlocStateManagementVariant() + ? '_onInit' + : 'init'; + final codeLines = List.empty(growable: true) + + ///Create BLoC class code + ..add("import 'dart:async';") + ..addNewLine() + ..add("import 'package:onix_flutter_bloc/onix_flutter_bloc.dart';"); + if (stateManagement == const BlocStateManagementVariant()) { + codeLines.add("import 'package:flutter_bloc/flutter_bloc.dart';"); + } + codeLines + ..add( + "import 'package:$projectName/presentation/screen/${screenClassImport}_screen/bloc/${screenClassImport}_screen_imports.dart';", + ) + ..addNewLine() + ..add( + 'class $className extends Base$stateManagementSuffix<$eventName$stateName, $srName> {'); + + final defaultStatePrefix = + stateManagement == const BlocStateManagementVariant() ? '' : 'const '; + final constructorSuffix = + stateManagement == const BlocStateManagementVariant() ? ' {' : ';'; + codeLines.add( + '$className() : super($defaultStatePrefix$stateName())$constructorSuffix'); + if (stateManagement == const BlocStateManagementVariant()) { + codeLines + ..add('on<${screenName.pascalCase}ScreenEventInit>(_onInit);') + ..add('add(const ${screenName.pascalCase}ScreenEvent.init());') + ..add('}'); + } + codeLines + ..addNewLine() + ..addNewLine() + ..add('void $initFunctionName ('); + if (stateManagement == const BlocStateManagementVariant()) { + codeLines + ..add('${screenName.pascalCase}ScreenEventInit event,') + ..add('Emitter<${screenName.pascalCase}ScreenState> emit,'); + } + codeLines.add(') {'); + if (stateManagement == const CubitStateManagementVariant()) { + codeLines.add('emit(state.copyWith(isLoading: false));'); + } + codeLines + ..add('}') + ..addNewLine() + ..add('}'); + return codeLines.join('\n'); + } + + String createBlocModels({ + required String screenName, + required StateManagementVariant stateManagement, + }) { + final screenModelName = screenName.pascalCase; + final screenClassImport = screenName.snakeCase; + final codeLines = List.empty(growable: true) + ..add("import 'package:freezed_annotation/freezed_annotation.dart';") + ..addNewLine() + ..add("part '${screenClassImport}_screen_models.freezed.dart';"); + + ///If BLoC - add Event model + if (stateManagement == const BlocStateManagementVariant()) { + codeLines + ..add('@freezed') + ..add( + 'class ${screenModelName}ScreenEvent with _\$${screenModelName}ScreenEvent {', + ) + ..add( + 'const factory ${screenModelName}ScreenEvent.init() = ${screenModelName}ScreenEventInit;', + ) + ..add('}'); + } + codeLines + ..addNewLine() + + ///Add SR events + ..add('@freezed') + ..add( + 'class ${screenModelName}ScreenSR with _\$${screenModelName}ScreenSR {', + ) + ..add( + 'const factory ${screenModelName}ScreenSR.loadFinished() = _LoadFinished;', + ) + ..add('}') + ..addNewLine(); + + ///Add BLoC State + if (stateManagement == const BlocStateManagementVariant()) { + codeLines.add('class ${screenModelName}ScreenState {}'); + } else { + codeLines + ..add('@freezed') + ..add( + 'class ${screenModelName}ScreenState with _\$${screenModelName}ScreenState{', + ) + ..add('const factory ${screenModelName}ScreenState({') + ..add('@Default(true) bool isLoading,') + ..add('}) = _${screenName.pascalCase}ScreenState;') + ..add('}'); + } + codeLines.addNewLine(); + return codeLines.join('\n'); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/mixins/di_content_mixin.dart b/lib/domain/service/file_generator_service/screen_generators/gen/mixins/di_content_mixin.dart new file mode 100644 index 00000000..ccd34ee1 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/mixins/di_content_mixin.dart @@ -0,0 +1,55 @@ +import 'dart:io'; + +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:recase/recase.dart'; + +mixin DIContentMixin on ScreenGenerationService { + final _importsSuffix = '//{imports end}'; + + Future createScreenDIContent({ + required ScreenGeneratorParams params, + }) async { + var stateManagement = params.screen.stateVariant.name.toLowerCase(); + final stateVariant = params.screen.stateVariant.name; + + if (stateManagement.startsWith('riverpod')) { + stateManagement = 'riverpod'; + } + + if (stateManagement.startsWith('cubit')) { + stateManagement = 'bloc'; + } + + final diFile = File( + '${params.projectPath}/${params.projectName}/lib/core/di/$stateManagement.dart'); + final screenName = params.normalizedScreenName; + var output = await diFile.readAsString(); + + final diSuffix = '//{$stateManagement end}'; + + final projectName = params.projectName; + + if (stateManagement == 'riverpod') { + output = output + .replaceFirst(_importsSuffix, + "import 'package:$projectName/presentation/screen/${screenName}_screen/riverpod/${screenName}_screen_imports.dart';\n$_importsSuffix") + .replaceFirst(diSuffix, + 'getIt.registerSingleton>(StateNotifierProvider<${screenName.pascalCase}ScreenProvider, ${screenName.pascalCase}ScreenState>((ref) => ${screenName.pascalCase}ScreenProvider(),),);\n$diSuffix'); + + output = ''' +$output + + StateNotifierProvider<${screenName.pascalCase}ScreenProvider, ${screenName.pascalCase}ScreenState> ${screenName.snakeCase}ScreenProvider() => + GetIt.I.get>(); + '''; + } else { + output = output + .replaceFirst(_importsSuffix, + "import 'package:$projectName/presentation/screen/${screenName}_screen/$stateManagement/${screenName}_screen_${stateVariant.toLowerCase()}.dart';\n$_importsSuffix") + .replaceFirst(diSuffix, + 'getIt.registerFactory<${screenName.pascalCase}Screen${stateVariant.pascalCase}>(${screenName.pascalCase}Screen${stateVariant.pascalCase}.new);\n$diSuffix'); + } + await diFile.writeAsString(output); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/mixins/provider_content_mixin.dart b/lib/domain/service/file_generator_service/screen_generators/gen/mixins/provider_content_mixin.dart new file mode 100644 index 00000000..7dc72c2f --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/mixins/provider_content_mixin.dart @@ -0,0 +1,39 @@ +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; +import 'package:recase/recase.dart'; + +mixin ProviderContentMixin on ScreenGenerationService { + String createProviderContent({ + required String projectName, + required String screenName, + }) { + ///Declare Provider classes names + final stateManagementSuffix = const ProviderStateManagementVariant().name; + final screenModelName = screenName.pascalCase; + final className = '${screenName.pascalCase}Screen$stateManagementSuffix'; + + final codeLines = List.empty(growable: true) + + ///Create Provider class code + ..add("import 'dart:async';") + ..addNewLine() + ..add( + "import 'package:onix_flutter_provider/onix_flutter_provider.dart';", + ) + ..addNewLine() + ..add('class $className extends BaseProvider {') + ..add('${screenModelName}ScreenProvider() : super() {') + ..add('init();') + ..add('}') + ..addNewLine() + ..add('void init() {') + ..add('// Add your initialization code here') + ..add('notifyListeners();') + ..add('}') + ..add('}') + ..addNewLine(); + + return codeLines.join('\n'); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/mixins/riverpod_content_mixin.dart b/lib/domain/service/file_generator_service/screen_generators/gen/mixins/riverpod_content_mixin.dart new file mode 100644 index 00000000..8f0a7e77 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/mixins/riverpod_content_mixin.dart @@ -0,0 +1,75 @@ +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; +import 'package:recase/recase.dart'; + +mixin RiverpodContentMixin on ScreenGenerationService { + String createRiverpodImportsContent({ + required String screenName, + required StateManagementVariant stateManagement, + }) { + final screenClassImport = screenName.snakeCase; + final codeLines = List.empty(growable: true) + ..add( + "export '${screenClassImport}_screen_provider.dart';", + ) + ..add("export '${screenClassImport}_screen_state.dart';") + ..addNewLine(); + return codeLines.join('\n'); + } + + String createRiverpodContent({ + required String projectName, + required String screenName, + required StateManagementVariant stateManagement, + }) { + final screenClassImport = screenName.snakeCase; + + final codeLines = List.empty(growable: true) + ..add("import 'package:flutter_riverpod/flutter_riverpod.dart';") + ..add( + "import 'package:$projectName/presentation/screen/${screenClassImport}_screen/riverpod/$screenClassImport\_screen_state.dart';", + ) + ..addNewLine() + ..add( + 'class ${screenName.pascalCase}ScreenProvider extends StateNotifier<${screenName.pascalCase}ScreenState> {', + ) + ..add( + '${screenName.pascalCase}ScreenProvider() : super(const ${screenName.pascalCase}ScreenState()) {init();}', + ) + ..addNewLine() + ..add('void init() {') + ..add('//state = state.copyWith(count: state.count + 1);') + ..add('}') + ..addNewLine() + ..add('//void increment() {') + ..add('//state = state.copyWith(count: state.count + 1);') + ..add('//}') + ..add('}'); + + return codeLines.join('\n'); + } + + String createRiverpodState({ + required String screenName, + required StateManagementVariant stateManagement, + }) { + final screenModelName = screenName.pascalCase; + final screenClassImport = screenName.snakeCase; + final codeLines = List.empty(growable: true) + ..add("import 'package:freezed_annotation/freezed_annotation.dart';") + ..addNewLine() + ..add("part '${screenClassImport}_screen_state.freezed.dart';") + ..addNewLine() + ..add('@freezed') + ..add( + 'class ${screenModelName}ScreenState with _\$${screenModelName}ScreenState {', + ) + ..add('const factory ${screenModelName}ScreenState({') + ..add('@Default(0) int count,') + ..add('}) = _${screenModelName}ScreenState;') + ..add('}') + ..addNewLine(); + return codeLines.join('\n'); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/provider_screen_code_content.dart b/lib/domain/service/file_generator_service/screen_generators/gen/provider_screen_code_content.dart new file mode 100644 index 00000000..67679afe --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/provider_screen_code_content.dart @@ -0,0 +1,74 @@ +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart'; +import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; +import 'package:recase/recase.dart'; + +class ProviderScreenCodeContent extends ScreenCodeContent { + @override + String createScreen({ + required bool isGoRouter, + required String screenName, + required String projectName, + }) { + final screenClassName = screenName.pascalCase; + final screenClassImport = screenName.snakeCase; + final codeLines = List.empty(growable: true) + + ///Add imports + ..add("import 'package:flutter/material.dart';"); + if (!isGoRouter) { + codeLines.add("import 'package:auto_route/annotations.dart';"); + } + + codeLines + ..add("import 'package:get_it/get_it.dart';") + ..add( + "import 'package:onix_flutter_provider/onix_flutter_provider.dart';", + ) + ..add( + "import 'package:$projectName/presentation/screen/${screenClassImport}_screen/provider/${screenClassImport}_screen_provider.dart';", + ) + ..addNewLine(); + + ///Add annotation in AutoRoute navigation used + if (!isGoRouter) { + codeLines.add('@RoutePage()'); + } + + ///Add screen widget code + codeLines + ..add('class ${screenClassName}Screen extends StatefulWidget {') + ..add('const ${screenClassName}Screen({') + ..add('super.key,') + ..add('});') + ..addNewLine() + ..add('@override') + ..add( + 'State<${screenClassName}Screen> createState() => _${screenClassName}ScreenState();', + ) + ..add('}') + ..addNewLine() + + ///Add screen widget state code + ..add('class _${screenClassName}ScreenState') + ..add('extends BaseProviderState<') + ..add('${screenClassName}ScreenProvider, ') + ..add('${screenClassName}Screen> {') + ..add('@override') + ..add( + '${screenClassName}ScreenProvider createProvider() => GetIt.I<${screenClassName}ScreenProvider>();', + ) + ..addNewLine() + ..add('@override') + ..add('Widget buildWidget(BuildContext context) {') + ..add('return Scaffold(') + ..add('body: SizedBox.expand(') + ..add('child: providerConsumer(') + ..add('stateListener: (provider) => const Center(') + ..add("child: Text('$screenClassName screen'),") + ..add('),') + ..add('),),);}}') + ..addNewLine(); + + return codeLines.join('\n'); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/riverpod_stateful_screen_code_content.dart b/lib/domain/service/file_generator_service/screen_generators/gen/riverpod_stateful_screen_code_content.dart new file mode 100644 index 00000000..81fee948 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/riverpod_stateful_screen_code_content.dart @@ -0,0 +1,54 @@ +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart'; +import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; +import 'package:recase/recase.dart'; + +class RiverpodStatefulScreenCodeContent extends ScreenCodeContent { + @override + String createScreen({ + required bool isGoRouter, + required String screenName, + required String projectName, + }) { + final screenClassName = screenName.pascalCase; + final codeLines = List.empty(growable: true); + + ///Add imports + if (!isGoRouter) { + codeLines.add("import 'package:auto_route/annotations.dart';"); + } + codeLines + ..add("import 'package:flutter/material.dart';") + ..add("import 'package:flutter_riverpod/flutter_riverpod.dart';") + ..add("import 'package:$projectName/core/di/riverpod.dart';") + ..addNewLine(); + + ///Add annotation in AutoRoute navigation used + if (!isGoRouter) { + codeLines.add('@RoutePage()'); + } + + ///Add screen widget code + codeLines + ..add('class ${screenClassName}Screen extends ConsumerStatefulWidget {') + ..add('const ${screenClassName}Screen({super.key});') + ..addNewLine() + ..add('@override') + ..add( + 'ConsumerState<${screenClassName}Screen> createState() => _${screenClassName}State();', + ) + ..add('}') + ..add( + 'class _${screenClassName}State extends ConsumerState<${screenClassName}Screen> {', + ) + ..add('@override') + ..add('Widget build(BuildContext context) {') + ..add('return const Scaffold(') + ..add("body: Center(child: Text('$screenClassName screen'),),") + ..add(');') + ..add('}') + ..add('}') + ..addNewLine(); + + return codeLines.join('\n'); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/riverpod_stateless_screen_code_content.dart b/lib/domain/service/file_generator_service/screen_generators/gen/riverpod_stateless_screen_code_content.dart new file mode 100644 index 00000000..34ea93c4 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/riverpod_stateless_screen_code_content.dart @@ -0,0 +1,46 @@ +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart'; +import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; +import 'package:recase/recase.dart'; + +class RiverpodStatelessScreenCodeContent extends ScreenCodeContent { + @override + String createScreen({ + required bool isGoRouter, + required String screenName, + required String projectName, + }) { + final screenClassName = screenName.pascalCase; + final codeLines = List.empty(growable: true); + + ///Add imports + if (!isGoRouter) { + codeLines.add("import 'package:auto_route/annotations.dart';"); + } + codeLines + ..add("import 'package:flutter/material.dart';") + ..add("import 'package:flutter_riverpod/flutter_riverpod.dart';") + ..add("import 'package:$projectName/core/di/riverpod.dart';") + ..addNewLine(); + + ///Add annotation in AutoRoute navigation used + if (!isGoRouter) { + codeLines.add('@RoutePage()'); + } + + ///Add screen widget code + codeLines + ..add('class ${screenClassName}Screen extends ConsumerWidget {') + ..add('const ${screenClassName}Screen({super.key});') + ..addNewLine() + ..add('@override') + ..add('Widget build(BuildContext context, WidgetRef ref) {') + ..add('return const Scaffold(') + ..add("body: Center(child: Text('$screenClassName screen'),),") + ..add(');') + ..add('}') + ..add('}') + ..addNewLine(); + + return codeLines.join('\n'); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart b/lib/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart index ce77a4ec..51357a6f 100644 --- a/lib/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart +++ b/lib/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart @@ -1,39 +1,22 @@ -import 'package:onix_flutter_bricks/domain/entity/screen/screen.dart'; import 'package:onix_flutter_bricks/util/enum/project_router.dart'; -import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; import 'package:recase/recase.dart'; -class ScreenCodeContent { - final _routesDeclarationSuffix = '//{routes declaration end}'; - final _navigatorRoutesSuffix = '//{routes end}'; - final _navigatorImportsSuffix = '//{imports end}'; - final _diBlocSuffix = '//{bloc end}'; - - String createScreenDIContent({ - required String input, - required String screenName, - required String projectName, - required ScreenStateManager stateManagement, - }) { - String output = input; - output = output - .replaceFirst(_navigatorImportsSuffix, - 'import \'package:$projectName/presentation/screen/${screenName}_screen/bloc/${screenName}_screen_${stateManagement.name}.dart\';\n$_navigatorImportsSuffix') - .replaceFirst(_diBlocSuffix, - 'getIt.registerFactory<${screenName.pascalCase}Screen${stateManagement.name.pascalCase}>(${screenName.pascalCase}Screen${stateManagement.name.pascalCase}.new);\n$_diBlocSuffix'); - return output; - } +abstract class ScreenCodeContent { + final routesDeclarationSuffix = '//{routes declaration end}'; + final navigatorRoutesSuffix = '//{routes end}'; + final navigatorImportsSuffix = '//{imports end}'; String createScreenNavigationGoRoute({ required String input, required String screenName, required bool isLastDeclaration, }) { - String output = input; + final output = input; final coda = isLastDeclaration ? ';' : ','; - output = output.replaceAll(_routesDeclarationSuffix, - '${screenName.camelCase}(\'/${screenName.snakeCase}\')$coda\n$_routesDeclarationSuffix'); - return output; + return output.replaceAll( + routesDeclarationSuffix, + "${screenName.camelCase}('/${screenName.snakeCase}')$coda\n$routesDeclarationSuffix", + ); } String createScreenNavigationContent({ @@ -43,296 +26,69 @@ class ScreenCodeContent { required bool isInitialScreen, required ProjectRouter router, }) { - String output = input; + var output = input; final screenClassImport = screenName.snakeCase; ///Declare initial route if (isInitialScreen) { - output = output.replaceAll('static const _initialLocation = \'/\'', - 'static const _initialLocation = \'/${screenName.snakeCase}\''); + output = output.replaceAll( + "static const _initialLocation = '/'", + "static const _initialLocation = '/${screenName.snakeCase}'", + ); } if (router == ProjectRouter.goRouter) { final goRouteContent = _buildGoRouteContent(screenName); output = output .replaceAll( - _navigatorRoutesSuffix, '$goRouteContent$_navigatorRoutesSuffix') - .replaceAll(_navigatorImportsSuffix, - 'import \'package:$projectName/presentation/screen/${screenClassImport}_screen/${screenClassImport}_screen.dart\';\n$_navigatorImportsSuffix'); + navigatorRoutesSuffix, '$goRouteContent$navigatorRoutesSuffix') + .replaceAll( + navigatorImportsSuffix, + "import 'package:$projectName/presentation/screen/${screenClassImport}_screen/${screenClassImport}_screen.dart';\n$navigatorImportsSuffix", + ); } else { final autoRouteContent = _buildAutoRouteContent( isInitialScreen, screenName, ); output = output - .replaceAll(_navigatorRoutesSuffix, - '$autoRouteContent\n$_navigatorRoutesSuffix') - .replaceAll(_navigatorImportsSuffix, - 'import \'package:$projectName/presentation/screen/${screenClassImport}_screen/${screenClassImport}_screen.dart\';$_navigatorImportsSuffix'); + .replaceAll(navigatorRoutesSuffix, + '$autoRouteContent\n$navigatorRoutesSuffix') + .replaceAll( + navigatorImportsSuffix, + "import 'package:$projectName/presentation/screen/${screenClassImport}_screen/${screenClassImport}_screen.dart';$navigatorImportsSuffix", + ); } return output; } - String _buildGoRouteContent(String screenName) { - final codeLines = List.empty(growable: true); - codeLines.add('GoRoute('); - codeLines.add('path: AppRoute.${screenName.camelCase}.routePath,'); - codeLines.add('name: AppRoute.${screenName.camelCase}.name,'); - codeLines.add('builder: (context, state) =>'); - codeLines.add('const ${screenName.pascalCase}Screen(),'); - codeLines.add(' ),'); - return codeLines.join('\n'); - } - String _buildAutoRouteContent( bool isInitialScreen, String screenName, ) { - final codeLines = List.empty(growable: true); - codeLines.add('AdaptiveRoute('); - codeLines.add('page: ${screenName.pascalCase}Route.page,'); - codeLines.add('path: \'/${screenName.camelCase}Screen\','); - codeLines.add(isInitialScreen ? 'initial: true,' : ''); - codeLines.add('),'); - return codeLines.join('\n'); - } - - String createBlocImportsContent({ - required String screenName, - required ScreenStateManager stateManagement, - }) { - final screenClassImport = screenName.snakeCase; - final codeLines = List.empty(growable: true); - codeLines.add( - 'export \'${screenClassImport}_screen_${stateManagement.name}.dart\';'); - codeLines.add('export \'${screenClassImport}_screen_models.dart\';'); - codeLines.addNewLine(); - return codeLines.join('\n'); - } - - String createBlocContent({ - required String projectName, - required String screenName, - required ScreenStateManager stateManagement, - }) { - ///Declare BLoC classes names - final stateManagementSuffix = stateManagement.name.pascalCase; - final screenClassImport = screenName.snakeCase; - final className = '${screenName.pascalCase}Screen$stateManagementSuffix'; - final eventName = stateManagement == ScreenStateManager.bloc - ? '${screenName.pascalCase}ScreenEvent, ' - : ''; - final stateName = '${screenName.pascalCase}ScreenState'; - final srName = '${screenName.pascalCase}ScreenSR'; - final initFunctionName = - stateManagement == ScreenStateManager.bloc ? '_onInit' : 'init'; - final codeLines = List.empty(growable: true); - - ///Create BLoC class code - codeLines.add('import \'dart:async\';'); - codeLines.addNewLine(); - codeLines.add( - 'import \'package:$projectName/core/arch/bloc/base_${stateManagement.name}.dart\';'); - if (stateManagement == ScreenStateManager.bloc) { - codeLines.add('import \'package:flutter_bloc/flutter_bloc.dart\';'); - } - codeLines.add( - 'import \'package:$projectName/presentation/screen/${screenClassImport}_screen/bloc/${screenClassImport}_screen_imports.dart\';'); - codeLines.addNewLine(); - codeLines.add( - 'class $className extends Base$stateManagementSuffix<$eventName$stateName, $srName> {'); - - final defaultStatePrefix = - stateManagement == ScreenStateManager.bloc ? '' : 'const '; - final constructorSuffix = - stateManagement == ScreenStateManager.bloc ? ' {' : ';'; - codeLines.add( - '$className() : super($defaultStatePrefix$stateName())$constructorSuffix'); - if (stateManagement == ScreenStateManager.bloc) { - codeLines.add('on<${screenName.pascalCase}ScreenEventInit>(_onInit);'); - codeLines.add('add(const ${screenName.pascalCase}ScreenEvent.init());'); - codeLines.add('}'); - } - codeLines.addNewLine(); - - codeLines.addNewLine(); - codeLines.add('FutureOr $initFunctionName ('); - if (stateManagement == ScreenStateManager.bloc) { - codeLines.add('${screenName.pascalCase}ScreenEventInit event,'); - codeLines.add('Emitter<${screenName.pascalCase}ScreenState> emit,'); - } - codeLines.add(') {'); - if (stateManagement == ScreenStateManager.cubit) { - codeLines.add('emit(state.copyWith(isLoading: false));'); - } - codeLines.add('}'); - codeLines.addNewLine(); - codeLines.add('}'); + final codeLines = List.empty(growable: true) + ..add('AdaptiveRoute(') + ..add('page: ${screenName.pascalCase}Route.page,') + ..add("path: '/${screenName.camelCase}Screen',") + ..add(isInitialScreen ? 'initial: true,' : '') + ..add('),'); return codeLines.join('\n'); } - String createBlocModels({ - required String screenName, - required ScreenStateManager stateManagement, - }) { - final screenModelName = screenName.pascalCase; - final screenClassImport = screenName.snakeCase; - final codeLines = List.empty(growable: true); - codeLines - .add('import \'package:freezed_annotation/freezed_annotation.dart\';'); - codeLines.addNewLine(); - codeLines.add('part \'${screenClassImport}_screen_models.freezed.dart\';'); - - ///If BLoC - add Event model - if (stateManagement == ScreenStateManager.bloc) { - codeLines.add('@freezed'); - codeLines.add( - 'class ${screenModelName}ScreenEvent with _\$${screenModelName}ScreenEvent {'); - codeLines.add( - 'const factory ${screenModelName}ScreenEvent.init() = ${screenModelName}ScreenEventInit;'); - codeLines.add('}'); - } - codeLines.addNewLine(); - - ///Add SR events - codeLines.add('@freezed'); - codeLines.add( - 'class ${screenModelName}ScreenSR with _\$${screenModelName}ScreenSR {'); - codeLines.add( - 'const factory ${screenModelName}ScreenSR.loadFinished() = _LoadFinished;'); - codeLines.add('}'); - codeLines.addNewLine(); - - ///Add BLoC State - if (stateManagement == ScreenStateManager.bloc) { - codeLines.add('class ${screenModelName}ScreenState {}'); - } else { - codeLines.add('@freezed'); - codeLines.add( - 'class ${screenModelName}ScreenState with _\$${screenModelName}ScreenState{'); - codeLines.add('const factory ${screenModelName}ScreenState({'); - codeLines.add('@Default(true) bool isLoading,'); - codeLines.add('}) = _${screenName.pascalCase}ScreenState;'); - codeLines.add('}'); - } - codeLines.addNewLine(); - return codeLines.join('\n'); - } - - String createNoStateManagementScreen({ - required bool isGoRouter, - required String screenName, - }) { - final screenClassName = screenName.pascalCase; - final codeLines = List.empty(growable: true); - - ///Add imports - if (isGoRouter) { - codeLines.add('import \'package:go_router/go_router.dart\';'); - } else { - codeLines.add('import \'package:auto_route/annotations.dart\';'); - } - codeLines.add('import \'package:flutter/material.dart\';'); - codeLines.addNewLine(); - - ///Add annotation in AutoRoute navigation used - if (!isGoRouter) { - codeLines.add('@RoutePage()'); - } - - ///Add screen widget code - codeLines.add('class ${screenClassName}Screen extends StatelessWidget {'); - codeLines.add('const ${screenClassName}Screen({super.key});'); - codeLines.addNewLine(); - codeLines.add('@override'); - codeLines.add('Widget build(BuildContext context) {'); - codeLines.add('return const Scaffold('); - codeLines.add('body: Center(child: Text(\'$screenClassName screen\'),),'); - codeLines.add(');'); - codeLines.add('}'); - codeLines.add('}'); - codeLines.addNewLine(); - + String _buildGoRouteContent(String screenName) { + final codeLines = List.empty(growable: true) + ..add('GoRoute(') + ..add('path: AppRoute.${screenName.camelCase}.routePath,') + ..add('name: AppRoute.${screenName.camelCase}.name,') + ..add('builder: (context, state) =>') + ..add('const ${screenName.pascalCase}Screen(),') + ..add(' ),'); return codeLines.join('\n'); } - String createStateManagementScreen({ + String createScreen({ required bool isGoRouter, required String screenName, required String projectName, - required ScreenStateManager stateManagement, - }) { - final screenClassName = screenName.pascalCase; - final screenClassImport = screenName.snakeCase; - final codeLines = List.empty(growable: true); - - ///Add imports - codeLines.add('import \'package:flutter/material.dart\';'); - if (!isGoRouter) { - codeLines.add('import \'package:auto_route/annotations.dart\';'); - } - if (stateManagement == ScreenStateManager.bloc) { - codeLines.add( - 'import \'package:$projectName/core/arch/bloc/base_bloc_state.dart\';'); - } else { - codeLines.add( - 'import \'package:$projectName/core/arch/bloc/base_cubit_state.dart\';'); - } - codeLines.add( - 'import \'package:$projectName/presentation/screen/${screenClassImport}_screen/bloc/${screenClassImport}_screen_imports.dart\';'); - codeLines.addNewLine(); - - ///Add annotation in AutoRoute navigation used - if (!isGoRouter) { - codeLines.add('@RoutePage()'); - } - - ///Add screen widget code - codeLines.add('class ${screenClassName}Screen extends StatefulWidget {'); - codeLines.add('const ${screenClassName}Screen({'); - codeLines.add('super.key,'); - codeLines.add('});'); - codeLines.addNewLine(); - codeLines.add('@override'); - codeLines.add( - 'State<${screenClassName}Screen> createState() => _${screenClassName}ScreenState();'); - codeLines.add('}'); - codeLines.addNewLine(); - - ///Add screen widget state code - codeLines.add('class _${screenClassName}ScreenState'); - codeLines.add( - 'extends Base${stateManagement == ScreenStateManager.cubit ? 'Cubit' : ''}State<'); - codeLines.add('${screenClassName}ScreenState, '); - codeLines - .add('${screenClassName}Screen${stateManagement.name.pascalCase}, '); - codeLines.add('${screenClassName}ScreenSR, '); - codeLines.add('${screenClassName}Screen> {'); - codeLines.add('@override'); - codeLines.add('Widget buildWidget(BuildContext context) {'); - codeLines.add('return srObserver('); - codeLines.add('context: context,'); - codeLines.add('child: Scaffold('); - codeLines.add('body: SizedBox.expand('); - codeLines.add('child: blocConsumer('); - codeLines.add('builder: (state) => const Center('); - codeLines.add('child: Text(\'$screenClassName screen\'),'); - codeLines.add('),'); - codeLines.add('listener: (context, state) {},'); - codeLines.add('),),),'); - codeLines.add('onSR: _onSingleResult,'); - codeLines.add(' );}'); - codeLines.addNewLine(); - - ///Add SR callback handler - codeLines.add( - 'void _onSingleResult(BuildContext context, ${screenClassName}ScreenSR singleResult) {'); - codeLines.add('singleResult.when('); - codeLines.add('loadFinished: () {'); - codeLines.add('},);}'); - codeLines.addNewLine(); - codeLines.add('}'); - codeLines.addNewLine(); - return codeLines.join('\n'); - } + }); } diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/stateful_screen_code_content.dart b/lib/domain/service/file_generator_service/screen_generators/gen/stateful_screen_code_content.dart new file mode 100644 index 00000000..374d61ea --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/stateful_screen_code_content.dart @@ -0,0 +1,52 @@ +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart'; +import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; +import 'package:recase/recase.dart'; + +class StatefulScreenCodeContent extends ScreenCodeContent { + @override + String createScreen({ + required bool isGoRouter, + required String screenName, + required String projectName, + }) { + final screenClassName = screenName.pascalCase; + final codeLines = List.empty(growable: true); + + ///Add imports + if (!isGoRouter) { + codeLines.add("import 'package:auto_route/annotations.dart';"); + } + codeLines + ..add("import 'package:flutter/material.dart';") + ..addNewLine(); + + ///Add annotation in AutoRoute navigation used + if (!isGoRouter) { + codeLines.add('@RoutePage()'); + } + + ///Add screen widget code + codeLines + ..add('class ${screenClassName}Screen extends StatefulWidget {') + ..add('const ${screenClassName}Screen({super.key});') + ..addNewLine() + ..add('@override') + ..add( + 'State<${screenClassName}Screen> createState() => _${screenClassName}State();', + ) + ..add('}') + ..add( + 'class _${screenClassName}State extends State<${screenClassName}Screen> {', + ) + ..add('@override') + ..add('Widget build(BuildContext context) {') + ..add('return const Scaffold(') + ..add("body: Center(child: Text('$screenClassName screen'),),") + ..add(');') + ..add('}') + ..add('}') + ..addNewLine(); + + return codeLines.join('\n'); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/gen/stateless_screen_code_content.dart b/lib/domain/service/file_generator_service/screen_generators/gen/stateless_screen_code_content.dart new file mode 100644 index 00000000..fb5719e1 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/gen/stateless_screen_code_content.dart @@ -0,0 +1,44 @@ +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart'; +import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; +import 'package:recase/recase.dart'; + +class StatelessScreenCodeContent extends ScreenCodeContent { + @override + String createScreen({ + required bool isGoRouter, + required String screenName, + required String projectName, + }) { + final screenClassName = screenName.pascalCase; + final codeLines = List.empty(growable: true); + + ///Add imports + if (!isGoRouter) { + codeLines.add("import 'package:auto_route/annotations.dart';"); + } + codeLines + ..add("import 'package:flutter/material.dart';") + ..addNewLine(); + + ///Add annotation in AutoRoute navigation used + if (!isGoRouter) { + codeLines.add('@RoutePage()'); + } + + ///Add screen widget code + codeLines + ..add('class ${screenClassName}Screen extends StatelessWidget {') + ..add('const ${screenClassName}Screen({super.key});') + ..addNewLine() + ..add('@override') + ..add('Widget build(BuildContext context) {') + ..add('return const Scaffold(') + ..add("body: Center(child: Text('$screenClassName screen'),),") + ..add(');') + ..add('}') + ..add('}') + ..addNewLine(); + + return codeLines.join('\n'); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart b/lib/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart index a544e518..42eca169 100644 --- a/lib/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart +++ b/lib/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart @@ -1,6 +1,7 @@ import 'package:onix_flutter_bricks/domain/entity/screen/screen.dart'; import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/util/enum/project_router.dart'; +import 'package:recase/recase.dart'; class ScreenGeneratorParams implements BaseGenerationParams { final String projectPath; @@ -19,3 +20,9 @@ class ScreenGeneratorParams implements BaseGenerationParams { this.build = false, }); } + +extension ScreenNameNormalizer on ScreenGeneratorParams { + String get normalizedScreenName => screen.name.snakeCase.endsWith('_screen') + ? screen.name.snakeCase.substring(0, screen.name.length - 7) + : screen.name.snakeCase; +} diff --git a/lib/domain/service/file_generator_service/screen_generators/provider_screen_generator.dart b/lib/domain/service/file_generator_service/screen_generators/provider_screen_generator.dart new file mode 100644 index 00000000..fa1be9b8 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/provider_screen_generator.dart @@ -0,0 +1,97 @@ +import 'dart:io'; + +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/mixins/di_content_mixin.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/mixins/provider_content_mixin.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/provider_screen_code_content.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/util/enum/project_router.dart'; + +class ProviderScreenGenerator extends ScreenGenerationService + with DIContentMixin, ProviderContentMixin { + final _screenCodeContent = ProviderScreenCodeContent(); + + @override + Future generate(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + + final screenPath = + '${params.projectPath}/${params.projectName}/lib/presentation/screen/${screenName}_screen'; + await Directory(screenPath).create(recursive: true); + + ///Create screen files and Provider files for a screen + await _createFiles(params, screenPath); + + ///Add screen configuration to Navigation Router file + await _createRoutes(params); + + if (params.screen.stateVariant is! StatelessStateManagementVariant) { + ///Add DI configuration for state management + await createScreenDIContent(params: params); + } + + return true; + } + + Future _createRoutes(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + if (params.router == ProjectRouter.goRouter) { + final routesFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_route.dart'); + final routesContent = routesFile.readAsStringSync(); + //Generate routes enum for GoRouter + final appRoutesContent = _screenCodeContent.createScreenNavigationGoRoute( + input: routesContent, + screenName: screenName, + isLastDeclaration: params.lastScreenItem, + ); + await routesFile.writeAsString(appRoutesContent); + } + + final routerFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_router.dart'); + final routerContent = routerFile.readAsStringSync(); + + ///Create Navigator screen declarations + final filledRouterContent = + _screenCodeContent.createScreenNavigationContent( + input: routerContent, + screenName: screenName, + projectName: params.projectName, + isInitialScreen: params.screen.initial, + router: params.router, + ); + + await routerFile.writeAsString(filledRouterContent); + } + + Future _createFiles( + ScreenGeneratorParams params, + String screenPath, + ) async { + final screenName = params.normalizedScreenName; + final screenFile = + await File('$screenPath/${screenName}_screen.dart').create(); + + var screenContent = ''; + + screenContent = _screenCodeContent.createScreen( + isGoRouter: params.router == ProjectRouter.goRouter, + projectName: params.projectName, + screenName: screenName, + ); + + await screenFile.writeAsString(screenContent); + + ///Write Provider file + final providerFile = await File( + '$screenPath/provider/${screenName}_screen_${params.screen.stateVariant.name.toLowerCase()}.dart') + .create(recursive: true); + final providerFileContent = createProviderContent( + projectName: params.projectName, + screenName: screenName, + ); + await providerFile.writeAsString(providerFileContent); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/riverpod_stateful_screen_generator.dart b/lib/domain/service/file_generator_service/screen_generators/riverpod_stateful_screen_generator.dart new file mode 100644 index 00000000..80100e5e --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/riverpod_stateful_screen_generator.dart @@ -0,0 +1,123 @@ +import 'dart:io'; + +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/mixins/di_content_mixin.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/mixins/riverpod_content_mixin.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/riverpod_stateful_screen_code_content.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/util/enum/project_router.dart'; + +class RiverpodStatefulScreenGenerator extends ScreenGenerationService + with DIContentMixin, RiverpodContentMixin { + final _screenCodeContent = RiverpodStatefulScreenCodeContent(); + + @override + Future generate(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + + final screenPath = + '${params.projectPath}/${params.projectName}/lib/presentation/screen/${screenName}_screen'; + await Directory(screenPath).create(recursive: true); + + ///Create screen files and BLoC files for a screen + await _createFiles(params, screenPath); + + ///Add screen configuration to Navigation Router file + await _createRoutes(params); + + if (params.screen.stateVariant is! StatelessStateManagementVariant && + params.screen.stateVariant is! StatefulStateManagementVariant) { + ///Add DI configuration for state management + await createScreenDIContent(params: params); + } + + return true; + } + + Future _createRoutes(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + if (params.router == ProjectRouter.goRouter) { + final routesFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_route.dart'); + final routesContent = routesFile.readAsStringSync(); + //Generate routes enum for GoRouter + final appRoutesContent = _screenCodeContent.createScreenNavigationGoRoute( + input: routesContent, + screenName: screenName, + isLastDeclaration: params.lastScreenItem, + ); + await routesFile.writeAsString(appRoutesContent); + } + + final routerFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_router.dart'); + final routerContent = routerFile.readAsStringSync(); + + ///Create Navigator screen declarations + final filledRouterContent = + _screenCodeContent.createScreenNavigationContent( + input: routerContent, + screenName: screenName, + projectName: params.projectName, + isInitialScreen: params.screen.initial, + router: params.router, + ); + + await routerFile.writeAsString(filledRouterContent); + } + + Future _createFiles( + ScreenGeneratorParams params, + String screenPath, + ) async { + final screenName = params.normalizedScreenName; + final screenFile = + await File('$screenPath/${screenName}_screen.dart').create(); + + var screenContent = ''; + + screenContent = _screenCodeContent.createScreen( + isGoRouter: params.router == ProjectRouter.goRouter, + screenName: screenName, + projectName: params.projectName, + ); + + if (screenContent.isEmpty) { + return; + } + + await screenFile.writeAsString(screenContent); + + ///Write Riverpod imports file + final importsFile = + await File('$screenPath/riverpod/${screenName}_screen_imports.dart') + .create(recursive: true); + final importsContent = createRiverpodImportsContent( + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await importsFile.writeAsString(importsContent); + + ///Write Riverpod state file + final modelsFile = + await File('$screenPath/riverpod/${screenName}_screen_state.dart') + .create(); + final modelsContent = createRiverpodState( + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await modelsFile.writeAsString(modelsContent); + + ///Write Riverpod file + final blocFile = await File( + '$screenPath/riverpod/${screenName}_screen_provider.dart', + ).create(); + final blocFileContent = createRiverpodContent( + projectName: params.projectName, + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await blocFile.writeAsString(blocFileContent); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/riverpod_stateless_screen_generator.dart b/lib/domain/service/file_generator_service/screen_generators/riverpod_stateless_screen_generator.dart new file mode 100644 index 00000000..a0f96ec3 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/riverpod_stateless_screen_generator.dart @@ -0,0 +1,123 @@ +import 'dart:io'; + +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/mixins/di_content_mixin.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/mixins/riverpod_content_mixin.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/riverpod_stateless_screen_code_content.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/util/enum/project_router.dart'; + +class RiverpodStatelessScreenGenerator extends ScreenGenerationService + with DIContentMixin, RiverpodContentMixin { + final _screenCodeContent = RiverpodStatelessScreenCodeContent(); + + @override + Future generate(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + + final screenPath = + '${params.projectPath}/${params.projectName}/lib/presentation/screen/${screenName}_screen'; + await Directory(screenPath).create(recursive: true); + + ///Create screen files and Riverpod files for a screen + await _createFiles(params, screenPath); + + ///Add screen configuration to Navigation Router file + await _createRoutes(params); + + if (params.screen.stateVariant is! StatelessStateManagementVariant && + params.screen.stateVariant is! StatefulStateManagementVariant) { + ///Add DI configuration for state management + await createScreenDIContent(params: params); + } + + return true; + } + + Future _createRoutes(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + if (params.router == ProjectRouter.goRouter) { + final routesFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_route.dart', + ); + final routesContent = routesFile.readAsStringSync(); + //Generate routes enum for GoRouter + final appRoutesContent = _screenCodeContent.createScreenNavigationGoRoute( + input: routesContent, + screenName: screenName, + isLastDeclaration: params.lastScreenItem, + ); + await routesFile.writeAsString(appRoutesContent); + } + + final routerFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_router.dart', + ); + final routerContent = routerFile.readAsStringSync(); + + ///Create Navigator screen declarations + final filledRouterContent = + _screenCodeContent.createScreenNavigationContent( + input: routerContent, + screenName: screenName, + projectName: params.projectName, + isInitialScreen: params.screen.initial, + router: params.router, + ); + + await routerFile.writeAsString(filledRouterContent); + } + + Future _createFiles( + ScreenGeneratorParams params, + String screenPath, + ) async { + final screenName = params.normalizedScreenName; + final screenFile = + await File('$screenPath/${screenName}_screen.dart').create(); + + final screenContent = _screenCodeContent.createScreen( + isGoRouter: params.router == ProjectRouter.goRouter, + screenName: screenName, + projectName: params.projectName, + ); + + if (screenContent.isEmpty) { + return; + } + + await screenFile.writeAsString(screenContent); + + ///Write Riverpod imports file + final importsFile = + await File('$screenPath/riverpod/${screenName}_screen_imports.dart') + .create(recursive: true); + final importsContent = createRiverpodImportsContent( + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await importsFile.writeAsString(importsContent); + + ///Write Riverpod state file + final modelsFile = + await File('$screenPath/riverpod/${screenName}_screen_state.dart') + .create(); + final modelsContent = createRiverpodState( + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await modelsFile.writeAsString(modelsContent); + + ///Write Riverpod file + final blocFile = await File( + '$screenPath/riverpod/${screenName}_screen_provider.dart', + ).create(); + final blocFileContent = createRiverpodContent( + projectName: params.projectName, + screenName: screenName, + stateManagement: params.screen.stateVariant, + ); + await blocFile.writeAsString(blocFileContent); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/screen_generator.dart b/lib/domain/service/file_generator_service/screen_generators/screen_generator.dart deleted file mode 100644 index b01329e1..00000000 --- a/lib/domain/service/file_generator_service/screen_generators/screen_generator.dart +++ /dev/null @@ -1,156 +0,0 @@ -import 'dart:io'; - -import 'package:onix_flutter_bricks/domain/entity/screen/screen.dart'; -import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; -import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/screen_code_content.dart'; -import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; -import 'package:onix_flutter_bricks/util/enum/project_router.dart'; -import 'package:recase/recase.dart'; - -class ScreenGenerator implements BaseGenerationService { - final _screenCodeContent = ScreenCodeContent(); - - @override - Future generate(BaseGenerationParams params) async { - if (params is! ScreenGeneratorParams) { - return false; - } - - String screenName = params.screen.name.snakeCase; - - if (screenName.endsWith('_screen')) { - screenName = screenName.substring(0, screenName.length - 7); - } - - final screenPath = - '${params.projectPath}/${params.projectName}/lib/presentation/screen/${screenName}_screen'; - await Directory(screenPath).create(recursive: true); - - if (params.screen.stateManager != ScreenStateManager.none) { - await Directory('$screenPath/bloc').create(recursive: true); - } - - ///Create screen files and BLoC files for a screen - await _createFiles(params, screenPath); - - ///Add screen configuration to Navigation Router file - await _createRoutes(params); - - if (params.screen.stateManager != ScreenStateManager.none) { - ///Add DI configuration for state management - await _createDI(params); - } - return true; - } - - Future _createRoutes(ScreenGeneratorParams params) async { - final screenName = params.screen.name; - if (params.router == ProjectRouter.goRouter) { - final routesFile = File( - '${params.projectPath}/${params.projectName}/lib/app/router/app_route.dart'); - String routesContent = routesFile.readAsStringSync(); - //Generate routes enum for GoRouter - final appRoutesContent = _screenCodeContent.createScreenNavigationGoRoute( - input: routesContent, - screenName: screenName, - isLastDeclaration: params.lastScreenItem, - ); - routesFile.writeAsString(appRoutesContent); - } - - final routerFile = File( - '${params.projectPath}/${params.projectName}/lib/app/router/app_router.dart'); - String routerContent = routerFile.readAsStringSync(); - - ///Create Navigator screen declarations - final filledRouterContent = - _screenCodeContent.createScreenNavigationContent( - input: routerContent, - screenName: screenName, - projectName: params.projectName, - isInitialScreen: params.screen.initial, - router: params.router, - ); - - routerFile.writeAsString(filledRouterContent); - } - - Future _createDI(ScreenGeneratorParams params) async { - var diFile = File( - '${params.projectPath}/${params.projectName}/lib/core/di/bloc.dart'); - String screenName = params.screen.name.snakeCase; - String content = await diFile.readAsString(); - final diOutputContent = _screenCodeContent.createScreenDIContent( - input: content, - screenName: screenName, - projectName: params.projectName, - stateManagement: params.screen.stateManager, - ); - await diFile.writeAsString(diOutputContent); - } - - Future _createFiles( - ScreenGeneratorParams params, - String screenPath, - ) async { - final screenName = params.screen.name.snakeCase; - final screenFile = - await File('$screenPath/${screenName}_screen.dart').create(); - - switch (params.screen.stateManager) { - case ScreenStateManager.bloc || ScreenStateManager.cubit: - - ///Write screen file - final screenContent = _screenCodeContent.createStateManagementScreen( - isGoRouter: params.router == ProjectRouter.goRouter, - screenName: screenName, - projectName: params.projectName, - stateManagement: params.screen.stateManager, - ); - await screenFile.writeAsString(screenContent); - - ///Write BLoC imports file - var importsFile = - await File('$screenPath/bloc/${screenName}_screen_imports.dart') - .create(); - final importsContent = _screenCodeContent.createBlocImportsContent( - screenName: screenName, - stateManagement: params.screen.stateManager, - ); - await importsFile.writeAsString(importsContent); - - ///Write BLoC models file - var modelsFile = - await File('$screenPath/bloc/${screenName}_screen_models.dart') - .create(); - final modelsContent = _screenCodeContent.createBlocModels( - screenName: screenName, - stateManagement: params.screen.stateManager, - ); - await modelsFile.writeAsString(modelsContent); - - ///Write BLoC file - var blocFile = await File( - '$screenPath/bloc/${screenName}_screen_${params.screen.stateManager.name}.dart') - .create(); - final blocFileContent = _screenCodeContent.createBlocContent( - projectName: params.projectName, - screenName: screenName, - stateManagement: params.screen.stateManager, - ); - await blocFile.writeAsString(blocFileContent); - - break; - case ScreenStateManager.none: - - ///Write screen without state management - final screenContent = _screenCodeContent.createNoStateManagementScreen( - isGoRouter: params.router == ProjectRouter.goRouter, - screenName: screenName, - ); - await screenFile.writeAsString(screenContent); - break; - } - } -} diff --git a/lib/domain/service/file_generator_service/screen_generators/stateful_screen_generator.dart b/lib/domain/service/file_generator_service/screen_generators/stateful_screen_generator.dart new file mode 100644 index 00000000..2e9e2718 --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/stateful_screen_generator.dart @@ -0,0 +1,82 @@ +import 'dart:io'; + +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/stateful_screen_code_content.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/util/enum/project_router.dart'; + +class StatefulScreenGenerator extends ScreenGenerationService { + final _screenCodeContent = StatefulScreenCodeContent(); + + @override + Future generate(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + + final screenPath = + '${params.projectPath}/${params.projectName}/lib/presentation/screen/${screenName}_screen'; + await Directory(screenPath).create(recursive: true); + + ///Create screen files and BLoC files for a screen + await _createFiles(params, screenPath); + + ///Add screen configuration to Navigation Router file + await _createRoutes(params); + + return true; + } + + Future _createRoutes(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + if (params.router == ProjectRouter.goRouter) { + final routesFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_route.dart'); + final routesContent = routesFile.readAsStringSync(); + //Generate routes enum for GoRouter + final appRoutesContent = _screenCodeContent.createScreenNavigationGoRoute( + input: routesContent, + screenName: screenName, + isLastDeclaration: params.lastScreenItem, + ); + await routesFile.writeAsString(appRoutesContent); + } + + final routerFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_router.dart'); + final routerContent = routerFile.readAsStringSync(); + + ///Create Navigator screen declarations + final filledRouterContent = + _screenCodeContent.createScreenNavigationContent( + input: routerContent, + screenName: screenName, + projectName: params.projectName, + isInitialScreen: params.screen.initial, + router: params.router, + ); + + await routerFile.writeAsString(filledRouterContent); + } + + Future _createFiles( + ScreenGeneratorParams params, + String screenPath, + ) async { + final screenName = params.normalizedScreenName; + final screenFile = + await File('$screenPath/${screenName}_screen.dart').create(); + + var screenContent = ''; + + screenContent = _screenCodeContent.createScreen( + isGoRouter: params.router == ProjectRouter.goRouter, + screenName: screenName, + projectName: params.projectName, + ); + + if (screenContent.isEmpty) { + return; + } + + await screenFile.writeAsString(screenContent); + } +} diff --git a/lib/domain/service/file_generator_service/screen_generators/stateless_screen_generator.dart b/lib/domain/service/file_generator_service/screen_generators/stateless_screen_generator.dart new file mode 100644 index 00000000..3dcdb2bc --- /dev/null +++ b/lib/domain/service/file_generator_service/screen_generators/stateless_screen_generator.dart @@ -0,0 +1,83 @@ +import 'dart:io'; + +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/gen/stateless_screen_code_content.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/util/enum/project_router.dart'; +import 'package:recase/recase.dart'; + +class StatelessScreenGenerator extends ScreenGenerationService { + final _screenCodeContent = StatelessScreenCodeContent(); + + @override + Future generate(ScreenGeneratorParams params) async { + final screenName = params.normalizedScreenName; + + final screenPath = + '${params.projectPath}/${params.projectName}/lib/presentation/screen/${screenName}_screen'; + await Directory(screenPath).create(recursive: true); + + ///Create screen files and BLoC files for a screen + await _createFiles(params, screenPath); + + ///Add screen configuration to Navigation Router file + await _createRoutes(params); + + return true; + } + + Future _createRoutes(ScreenGeneratorParams params) async { + final screenName = params.screen.name; + if (params.router == ProjectRouter.goRouter) { + final routesFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_route.dart'); + final routesContent = routesFile.readAsStringSync(); + //Generate routes enum for GoRouter + final appRoutesContent = _screenCodeContent.createScreenNavigationGoRoute( + input: routesContent, + screenName: screenName, + isLastDeclaration: params.lastScreenItem, + ); + await routesFile.writeAsString(appRoutesContent); + } + + final routerFile = File( + '${params.projectPath}/${params.projectName}/lib/app/router/app_router.dart'); + final routerContent = routerFile.readAsStringSync(); + + ///Create Navigator screen declarations + final filledRouterContent = + _screenCodeContent.createScreenNavigationContent( + input: routerContent, + screenName: screenName, + projectName: params.projectName, + isInitialScreen: params.screen.initial, + router: params.router, + ); + + await routerFile.writeAsString(filledRouterContent); + } + + Future _createFiles( + ScreenGeneratorParams params, + String screenPath, + ) async { + final screenName = params.screen.name.snakeCase; + final screenFile = + await File('$screenPath/${screenName}_screen.dart').create(); + + var screenContent = ''; + + screenContent = _screenCodeContent.createScreen( + isGoRouter: params.router == ProjectRouter.goRouter, + screenName: screenName, + projectName: params.projectName, + ); + + if (screenContent.isEmpty) { + return; + } + + await screenFile.writeAsString(screenContent); + } +} diff --git a/lib/domain/service/file_generator_service/signing_generator/signing_generator.dart b/lib/domain/service/file_generator_service/signing_generator/signing_generator.dart index 65c5bcf7..a7a8411e 100644 --- a/lib/domain/service/file_generator_service/signing_generator/signing_generator.dart +++ b/lib/domain/service/file_generator_service/signing_generator/signing_generator.dart @@ -1,29 +1,25 @@ import 'dart:io'; import 'package:flutter/services.dart'; -import 'package:onix_flutter_bricks/core/arch/domain/entity/result/result.dart'; import 'package:onix_flutter_bricks/core/di/app.dart'; import 'package:onix_flutter_bricks/domain/entity/failure/signing_failure.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/signing_generator/params/signing_generator_params.dart'; import 'package:onix_flutter_bricks/domain/service/output_service/output_service.dart'; import 'package:onix_flutter_bricks/util/extension/output/output_message_extension.dart'; import 'package:onix_flutter_bricks/util/process_runner.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; -///This class Generates Android keystore with given credentials and fix Gradle signing configuration -class SigningGenerator implements BaseGenerationService> { +///This class Generates Android keystore with given credentials +///and fix Gradle signing configuration +class SigningGenerator + implements BaseGenerationService, SingingGeneratorParams> { final OutputService _outputService; SigningGenerator(this._outputService); @override - Future> generate(BaseGenerationParams params) async { - if (params is! SingingGeneratorParams) { - return Result.error( - failure: SigningFailure(SigningFailureType.invalidParams), - ); - } + Future> generate(SingingGeneratorParams params) async { try { _outputService .add('Keystore password: ${params.signingPassword}'.toInfoMessage()); @@ -36,7 +32,7 @@ class SigningGenerator implements BaseGenerationService> { await directory.create(); } final certificateFile = File('$workDirectory/upload-keystore.jks'); - final certificateExist = await certificateFile.exists(); + final certificateExist = certificateFile.existsSync(); if (certificateExist) { return Result.error( failure: SigningFailure(SigningFailureType.signingAlreadyExist), @@ -96,6 +92,11 @@ if (propFile.canRead()) { android.buildTypes.release.signingConfig = null }'''; + final signingConfigString = + buildGradleContent.contains('signingConfig = signingConfigs.debug') + ? 'signingConfig = signingConfigs.debug' + : 'signingConfig signingConfigs.debug'; + ///Fix build types configuration await buildGradle.writeAsString( buildGradleContent.replaceAll( @@ -103,7 +104,7 @@ if (propFile.canRead()) { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig signingConfigs.debug + $signingConfigString } }''', '''signingConfigs { diff --git a/lib/domain/service/file_generator_service/style_generator/colors_generator.dart b/lib/domain/service/file_generator_service/style_generator/colors_generator.dart index 6a35ef44..ee2483a3 100644 --- a/lib/domain/service/file_generator_service/style_generator/colors_generator.dart +++ b/lib/domain/service/file_generator_service/style_generator/colors_generator.dart @@ -1,21 +1,18 @@ import 'dart:io'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/gen/app_colors_file_content.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/colors_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/colors_generator_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/parser/colors_parser.dart'; -class ColorsGenerator implements BaseGenerationService { +class ColorsGenerator + implements BaseGenerationService { final _colorParser = ColorsParser(); final _appColorsGenerator = AppColorsFileContent(); @override - Future generate(BaseGenerationParams params) async { - if (params is! ColorsGeneratorParams) { - return false; - } + Future generate(ColorsGeneratorParams params) async { var themeColorsFile = await File( '${params.projectPath}/${params.projectName}/lib/presentation/style/app_colors.dart') .create(recursive: true); diff --git a/lib/domain/service/file_generator_service/style_generator/gen/app_colors_file_content.dart b/lib/domain/service/file_generator_service/style_generator/gen/app_colors_file_content.dart index 1d58e5f0..d020b8d6 100644 --- a/lib/domain/service/file_generator_service/style_generator/gen/app_colors_file_content.dart +++ b/lib/domain/service/file_generator_service/style_generator/gen/app_colors_file_content.dart @@ -1,16 +1,13 @@ import 'package:onix_flutter_bricks/domain/entity/app_styles/app_color_style.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/colors_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/style_generator_const.dart'; import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; -class AppColorsFileContent implements BaseGenerationService { +class AppColorsFileContent + implements BaseGenerationService { @override - Future generate(BaseGenerationParams params) async { - if (params is! ColorsGenerationParams) { - return ''; - } + Future generate(ColorsGenerationParams params) async { return _generateInternal(params.colors); } diff --git a/lib/domain/service/file_generator_service/style_generator/gen/theme_colors_file_content.dart b/lib/domain/service/file_generator_service/style_generator/gen/theme_colors_file_content.dart index 6f86a397..7e2679b3 100644 --- a/lib/domain/service/file_generator_service/style_generator/gen/theme_colors_file_content.dart +++ b/lib/domain/service/file_generator_service/style_generator/gen/theme_colors_file_content.dart @@ -1,19 +1,15 @@ import 'package:onix_flutter_bricks/domain/entity/app_styles/app_color_style.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/theme_colors_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/style_generator_const.dart'; import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; import 'package:onix_flutter_bricks/util/extension/swagger_extensions.dart'; import 'package:recase/recase.dart'; -class ThemeColorsFileContent implements BaseGenerationService { +class ThemeColorsFileContent + implements BaseGenerationService { @override - Future generate(BaseGenerationParams params) async { - if (params is! ThemeColorsGenerationParams) { - return ''; - } - + Future generate(ThemeColorsGenerationParams params) async { return _generateInternal( colors: params.colors, projectName: params.projectName, diff --git a/lib/domain/service/file_generator_service/style_generator/gen/theme_colors_file_content_tailor.dart b/lib/domain/service/file_generator_service/style_generator/gen/theme_colors_file_content_tailor.dart index b1504be3..e47fe127 100644 --- a/lib/domain/service/file_generator_service/style_generator/gen/theme_colors_file_content_tailor.dart +++ b/lib/domain/service/file_generator_service/style_generator/gen/theme_colors_file_content_tailor.dart @@ -1,17 +1,13 @@ import 'package:onix_flutter_bricks/domain/entity/app_styles/app_color_style.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/theme_colors_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/style_generator_const.dart'; import 'package:onix_flutter_bricks/util/extension/swagger_extensions.dart'; -class ThemeColorsFileContentTailor implements BaseGenerationService { +class ThemeColorsFileContentTailor + implements BaseGenerationService { @override - Future generate(BaseGenerationParams params) async { - if (params is! ThemeColorsGenerationParams) { - return ''; - } - + Future generate(ThemeColorsGenerationParams params) async { return _generateInternal( colors: params.colors, projectName: params.projectName, diff --git a/lib/domain/service/file_generator_service/style_generator/gen/theme_text_styles_file_content.dart b/lib/domain/service/file_generator_service/style_generator/gen/theme_text_styles_file_content.dart index 30146368..9da30e17 100644 --- a/lib/domain/service/file_generator_service/style_generator/gen/theme_text_styles_file_content.dart +++ b/lib/domain/service/file_generator_service/style_generator/gen/theme_text_styles_file_content.dart @@ -2,17 +2,14 @@ import 'package:collection/collection.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_color_style.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_text_style.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/theme_text_style_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/style_generator_const.dart'; import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; -class ThemeTextStylesFileContent implements BaseGenerationService { +class ThemeTextStylesFileContent + implements BaseGenerationService { @override - Future generate(BaseGenerationParams params) async { - if (params is! ThemeTextStyleGenerationParams) { - return ''; - } + Future generate(ThemeTextStyleGenerationParams params) async { return _generateInternal( textStyles: params.textStyles, colors: params.colors, diff --git a/lib/domain/service/file_generator_service/style_generator/gen/theme_text_styles_file_content_tailor.dart b/lib/domain/service/file_generator_service/style_generator/gen/theme_text_styles_file_content_tailor.dart index 54d32290..2a9c6bf2 100644 --- a/lib/domain/service/file_generator_service/style_generator/gen/theme_text_styles_file_content_tailor.dart +++ b/lib/domain/service/file_generator_service/style_generator/gen/theme_text_styles_file_content_tailor.dart @@ -2,16 +2,12 @@ import 'package:collection/collection.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_color_style.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_text_style.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/theme_text_style_generation_params.dart'; class ThemeTextStylesFileContentTailor - implements BaseGenerationService { + implements BaseGenerationService { @override - Future generate(BaseGenerationParams params) async { - if (params is! ThemeTextStyleGenerationParams) { - return ''; - } + Future generate(ThemeTextStyleGenerationParams params) async { return _generateInternal( textStyles: params.textStyles, colors: params.colors, diff --git a/lib/domain/service/file_generator_service/style_generator/parser/colors_parser.dart b/lib/domain/service/file_generator_service/style_generator/parser/colors_parser.dart index 57a42911..153de21b 100644 --- a/lib/domain/service/file_generator_service/style_generator/parser/colors_parser.dart +++ b/lib/domain/service/file_generator_service/style_generator/parser/colors_parser.dart @@ -53,11 +53,13 @@ class ColorsParser { ), ]); } else { - existingColors.add(AppColorStyle( - id: '', - name: name, - color: parsedColor, - )); + existingColors.add( + AppColorStyle( + id: '', + name: name, + color: parsedColor, + ), + ); } } } @@ -76,7 +78,11 @@ class ColorsParser { logger.f('parts: $parts'); return Color.fromRGBO( - parts[0].toInt(), parts[1].toInt(), parts[2].toInt(), parts[3]); + parts[0].toInt(), + parts[1].toInt(), + parts[2].toInt(), + parts[3], + ); } static Color _parseARGB(String color) { diff --git a/lib/domain/service/file_generator_service/style_generator/parser/text_styles_parser.dart b/lib/domain/service/file_generator_service/style_generator/parser/text_styles_parser.dart index 5d9955e2..5c67bb81 100644 --- a/lib/domain/service/file_generator_service/style_generator/parser/text_styles_parser.dart +++ b/lib/domain/service/file_generator_service/style_generator/parser/text_styles_parser.dart @@ -32,8 +32,10 @@ class TextStylesParser { } static void _parseTailor( - List lines, List existingTextStyles) { - for (var line in lines) { + List lines, + List existingTextStyles, + ) { + for (final line in lines) { if (line.contains('static List ')) { final startLine = line ..replaceAll('static List ', '') @@ -48,7 +50,7 @@ class TextStylesParser { continue; } - String styleContent = ''; + var styleContent = ''; var lineIndex = lines.indexOf(startLine) + 1; @@ -62,11 +64,11 @@ class TextStylesParser { .where((element) => element != '') .toList(); - for (var line in stylesLines) { + for (final line in stylesLines) { final styleLine = line.replaceAll('TextStyle(', '').replaceAll('//', ''); - Map styleMap = {}; + final styleMap = {}; for (final part in styleLine.split(',')) { final key = part.split(':')[0].trim(); @@ -80,10 +82,13 @@ class TextStylesParser { name: name, fontFamily: '', fontSize: double.tryParse( - (styleMap['fontSize'] ?? '').replaceAll('.sp', '')) ?? + (styleMap['fontSize'] ?? '').replaceAll('.sp', ''), + ) ?? 18, - fontWeight: int.tryParse((styleMap['fontWeight'] ?? '') - .replaceAll('FontWeight.w', '')) ?? + fontWeight: int.tryParse( + (styleMap['fontWeight'] ?? '') + .replaceAll('FontWeight.w', ''), + ) ?? 600, letterSpacing: double.tryParse(styleMap['letterSpacing'] ?? '') ?? 0, @@ -96,8 +101,10 @@ class TextStylesParser { } static void _parseManual( - List lines, List existingTextStyles) { - for (var line in lines) { + List lines, + List existingTextStyles, + ) { + for (final line in lines) { if (line.contains(': TextStyle(')) { final startLine = line; @@ -107,7 +114,7 @@ class TextStylesParser { continue; } - String styleContent = ''; + var styleContent = ''; var lineIndex = lines.indexOf(startLine) + 1; @@ -123,8 +130,8 @@ class TextStylesParser { logger.f(stylesLines); - for (var line in stylesLines) { - Map styleMap = {}; + for (final line in stylesLines) { + final styleMap = {}; final parts = line .replaceAll('//', '') @@ -144,10 +151,13 @@ class TextStylesParser { name: name, fontFamily: '', fontSize: double.tryParse( - (styleMap['fontSize'] ?? '').replaceAll('.sp', '')) ?? + (styleMap['fontSize'] ?? '').replaceAll('.sp', ''), + ) ?? 18, - fontWeight: int.tryParse((styleMap['fontWeight'] ?? '') - .replaceAll('FontWeight.w', '')) ?? + fontWeight: int.tryParse( + (styleMap['fontWeight'] ?? '') + .replaceAll('FontWeight.w', ''), + ) ?? 600, letterSpacing: double.tryParse(styleMap['letterSpacing'] ?? '') ?? 0, diff --git a/lib/domain/service/file_generator_service/style_generator/style_generator_const.dart b/lib/domain/service/file_generator_service/style_generator/style_generator_const.dart index 4d2aea00..33118627 100644 --- a/lib/domain/service/file_generator_service/style_generator/style_generator_const.dart +++ b/lib/domain/service/file_generator_service/style_generator/style_generator_const.dart @@ -1,6 +1,8 @@ -abstract final class StyleGeneratorConst { +class StyleGeneratorConst { static const lightColorsKey = 'light'; static const darkColorsKey = 'dark'; static const lightColorSuffix = 'Light'; static const darkColorSuffix = 'Dark'; + + const StyleGeneratorConst._(); } diff --git a/lib/domain/service/file_generator_service/style_generator/styles_generator.dart b/lib/domain/service/file_generator_service/style_generator/styles_generator.dart index b1997337..6a871711 100644 --- a/lib/domain/service/file_generator_service/style_generator/styles_generator.dart +++ b/lib/domain/service/file_generator_service/style_generator/styles_generator.dart @@ -1,7 +1,6 @@ import 'package:onix_flutter_bricks/domain/entity/app_styles/app_color_style.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_text_style.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/colors_generator.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/colors_generator_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/styles_generator_params.dart'; @@ -10,18 +9,17 @@ import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_ import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/theme_colors_generator.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/theme_text_styles_generator.dart'; -class StylesGenerator implements BaseGenerationService { - final BaseGenerationService _colorsGenerator = ColorsGenerator(); - final BaseGenerationService _themeColorsGenerator = - ThemeColorsGenerator(); - final BaseGenerationService _themeTextStylesGenerator = - ThemeTextStylesGenerator(); +class StylesGenerator + implements BaseGenerationService { + final BaseGenerationService _colorsGenerator = + ColorsGenerator(); + final BaseGenerationService + _themeColorsGenerator = ThemeColorsGenerator(); + final BaseGenerationService + _themeTextStylesGenerator = ThemeTextStylesGenerator(); @override - Future generate(BaseGenerationParams params) async { - if (params is! StylesGeneratorParams) { - return false; - } + Future generate(StylesGeneratorParams params) async { final colors = params.styles.whereType().toList(); final textStyles = params.styles.whereType().toList(); diff --git a/lib/domain/service/file_generator_service/style_generator/theme_colors_generator.dart b/lib/domain/service/file_generator_service/style_generator/theme_colors_generator.dart index 9cfdb6fe..fdf89fbe 100644 --- a/lib/domain/service/file_generator_service/style_generator/theme_colors_generator.dart +++ b/lib/domain/service/file_generator_service/style_generator/theme_colors_generator.dart @@ -1,7 +1,6 @@ import 'dart:io'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/gen/theme_colors_file_content.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/gen/theme_colors_file_content_tailor.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/theme_colors_generation_params.dart'; @@ -9,20 +8,18 @@ import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_ import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/parser/colors_parser.dart'; import 'package:onix_flutter_bricks/util/enum/project_theming.dart'; -class ThemeColorsGenerator implements BaseGenerationService { +class ThemeColorsGenerator + implements BaseGenerationService { final _colorParser = ColorsParser(); final _defaultColorsGenerator = ThemeColorsFileContent(); final _tailorColorsGenerator = ThemeColorsFileContentTailor(); @override - Future generate(BaseGenerationParams params) async { - if (params is! ThemeColorsGeneratorParams) { - return false; - } + Future generate(ThemeColorsGeneratorParams params) async { final libFolder = '${params.projectPath}/${params.projectName}/lib'; final appColorsFile = await File( - '$libFolder/presentation/style/theme/theme_extension/theme_colors.dart') - .create(recursive: true); + '$libFolder/presentation/style/theme/theme_extension/theme_colors.dart', + ).create(recursive: true); final themeColorsFile = File('$libFolder/presentation/style/app_colors.dart'); diff --git a/lib/domain/service/file_generator_service/style_generator/theme_text_styles_generator.dart b/lib/domain/service/file_generator_service/style_generator/theme_text_styles_generator.dart index 7a7d4e8b..c7ce0366 100644 --- a/lib/domain/service/file_generator_service/style_generator/theme_text_styles_generator.dart +++ b/lib/domain/service/file_generator_service/style_generator/theme_text_styles_generator.dart @@ -1,7 +1,6 @@ import 'dart:io'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/gen/theme_text_styles_file_content.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/gen/theme_text_styles_file_content_tailor.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/params/theme_text_style_generation_params.dart'; @@ -9,20 +8,18 @@ import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_ import 'package:onix_flutter_bricks/domain/service/file_generator_service/style_generator/parser/text_styles_parser.dart'; import 'package:onix_flutter_bricks/util/enum/project_theming.dart'; -class ThemeTextStylesGenerator implements BaseGenerationService { +class ThemeTextStylesGenerator + implements BaseGenerationService { final _textStylesParser = TextStylesParser(); final _defaultTextStylesGenerator = ThemeTextStylesFileContent(); final _tailorTextStylesGenerator = ThemeTextStylesFileContentTailor(); @override - Future generate(BaseGenerationParams params) async { - if (params is! ThemeTextStyleGeneratorParams) { - return false; - } + Future generate(ThemeTextStyleGeneratorParams params) async { final libFolder = '${params.projectPath}/${params.projectName}/lib'; final appTextStylesFile = await File( - '$libFolder/presentation/style/theme/theme_extension/theme_text_styles.dart') - .create(recursive: true); + '$libFolder/presentation/style/theme/theme_extension/theme_text_styles.dart', + ).create(recursive: true); final parsedTextStyles = _textStylesParser .parseFromFile( @@ -40,19 +37,21 @@ class ThemeTextStylesGenerator implements BaseGenerationService { if (params.theming == ProjectTheming.themeTailor) { final result = await _tailorTextStylesGenerator.generate( ThemeTextStyleGenerationParams( - textStyles: allTextStyles, - colors: params.colors, - projectName: params.projectName, - useScreenUtil: params.useScreenUtil), + textStyles: allTextStyles, + colors: params.colors, + projectName: params.projectName, + useScreenUtil: params.useScreenUtil, + ), ); await appTextStylesFile.writeAsString(result); } else { final result = await _defaultTextStylesGenerator.generate( ThemeTextStyleGenerationParams( - textStyles: allTextStyles, - colors: params.colors, - projectName: params.projectName, - useScreenUtil: params.useScreenUtil), + textStyles: allTextStyles, + colors: params.colors, + projectName: params.projectName, + useScreenUtil: params.useScreenUtil, + ), ); await appTextStylesFile.writeAsString(result); } diff --git a/lib/domain/service/git_cliff_service/git_cliff_service.dart b/lib/domain/service/git_cliff_service/git_cliff_service.dart index 8ecc7b8d..f08b4e20 100644 --- a/lib/domain/service/git_cliff_service/git_cliff_service.dart +++ b/lib/domain/service/git_cliff_service/git_cliff_service.dart @@ -3,20 +3,17 @@ import 'dart:io'; import 'package:flutter/services.dart'; import 'package:onix_flutter_bricks/core/di/app.dart'; import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/git_cliff_service/enums/git_cliff_asset.dart'; import 'package:onix_flutter_bricks/domain/service/git_cliff_service/params/git_cliff_params.dart'; import 'package:onix_flutter_bricks/util/extension/codelines_extension.dart'; import 'package:onix_flutter_bricks/util/makefile/makefile_content.dart'; import 'package:onix_flutter_bricks/util/makefile/makefile_line.dart'; -class GitCliffService implements BaseGenerationService { - @override - Future generate(BaseGenerationParams params) async { - if (params is! GitCliffParams) { - return 'Incorrect params'; - } +class GitCliffService implements BaseGenerationService { + const GitCliffService(); + @override + Future generate(GitCliffParams params) async { try { await _copyAndPasteFiles(params); await _updateMainMakeFile(params); @@ -65,7 +62,7 @@ class GitCliffService implements BaseGenerationService { commands: [ '@git cliff -c cliff_md.toml -o CHANGELOG.md', ], - ) + ), ], ); diff --git a/lib/domain/service/strategy/state_manager_strategy.dart b/lib/domain/service/strategy/state_manager_strategy.dart new file mode 100644 index 00000000..9be1259e --- /dev/null +++ b/lib/domain/service/strategy/state_manager_strategy.dart @@ -0,0 +1,13 @@ +import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/repository/screen_repository.dart'; + +abstract interface class StateManagerStrategy { + List get variants; + + Future generate({ + required Config config, + required ScreenRepository screenRepository, + required void Function(String) logResult, + }); +} diff --git a/lib/domain/service/strategy/strategies/base_strategy.dart b/lib/domain/service/strategy/strategies/base_strategy.dart new file mode 100644 index 00000000..b36359b1 --- /dev/null +++ b/lib/domain/service/strategy/strategies/base_strategy.dart @@ -0,0 +1,75 @@ +import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/repository/screen_repository.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/default_screen_route_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/default_screen_route_generator_params.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/domain/service/strategy/state_manager_strategy.dart'; +import 'package:onix_flutter_bricks/util/extension/output/output_message_extension.dart'; + +class BaseStrategy implements StateManagerStrategy { + final BaseGenerationService _defaultScreenRouteGenerator; + + BaseStrategy({ + required DefaultScreenRouteGenerator defaultScreenRouteGenerator, + }) : _defaultScreenRouteGenerator = defaultScreenRouteGenerator; + + @override + List get variants => [ + const StatefulStateManagementVariant(), + const StatelessStateManagementVariant(), + ]; + + @override + Future generate({ + required Config config, + required ScreenRepository screenRepository, + required void Function(String) logResult, + }) async { + try { + final screensNotExist = config.screens + .where( + (element) => !element.exists, + ) + .toList(); + + if (screensNotExist.isEmpty) { + await _defaultScreenRouteGenerator.generate( + DefaultScreenRouteGeneratorParams( + projectPath: config.projectPath, + projectName: config.projectName, + router: config.router, + ), + ); + } else { + for (var i = 0; i < screensNotExist.length; i++) { + final screen = screensNotExist[i]; + logResult( + 'Generating screen ${screen.name}...'.toInfoMessage(), + ); + + await screen.stateVariant.screenGenerator.generate( + ScreenGeneratorParams( + screen: screen, + projectPath: config.projectPath, + projectName: config.projectName, + router: config.router, + lastScreenItem: i == (screensNotExist.length - 1), + ), + ); + screen.exists = true; + screenRepository.modifyScreen(screen, screen.name); + } + } + + logResult( + 'Screens generated!'.toInfoMessage(), + ); + } catch (e) { + logResult( + 'Error generating screens: $e'.toErrorMessage(), + ); + } + } +} diff --git a/lib/domain/service/strategy/strategies/bloc_strategy.dart b/lib/domain/service/strategy/strategies/bloc_strategy.dart new file mode 100644 index 00000000..87918485 --- /dev/null +++ b/lib/domain/service/strategy/strategies/bloc_strategy.dart @@ -0,0 +1,73 @@ +import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/repository/screen_repository.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/default_screen_route_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/default_screen_route_generator_params.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/domain/service/strategy/state_manager_strategy.dart'; +import 'package:onix_flutter_bricks/util/extension/output/output_message_extension.dart'; + +class BlocStateManagerStrategy implements StateManagerStrategy { + final BaseGenerationService _defaultScreenRouteGenerator; + + BlocStateManagerStrategy({ + required DefaultScreenRouteGenerator defaultScreenRouteGenerator, + }) : _defaultScreenRouteGenerator = defaultScreenRouteGenerator; + + @override + List get variants => [ + const StatefulStateManagementVariant(), + const StatelessStateManagementVariant(), + const BlocStateManagementVariant(), + const CubitStateManagementVariant(), + ]; + + @override + Future generate({ + required Config config, + required ScreenRepository screenRepository, + required void Function(String) logResult, + }) async { + try { + final screensNotExist = config.screens + .where( + (element) => !element.exists, + ) + .toList(); + + if (screensNotExist.isEmpty) { + await _defaultScreenRouteGenerator.generate( + DefaultScreenRouteGeneratorParams( + projectPath: config.projectPath, + projectName: config.projectName, + router: config.router, + ), + ); + } else { + for (var i = 0; i < screensNotExist.length; i++) { + final screen = screensNotExist[i]; + logResult( + 'Generating screen ${screen.name}...'.toInfoMessage(), + ); + + await screen.stateVariant.screenGenerator.generate( + ScreenGeneratorParams( + screen: screen, + projectPath: config.projectPath, + projectName: config.projectName, + router: config.router, + lastScreenItem: i == (screensNotExist.length - 1), + ), + ); + screen.exists = true; + screenRepository.modifyScreen(screen, screen.name); + } + } + } catch (e) { + logResult( + 'Error generating screens: $e'.toErrorMessage(), + ); + } + } +} diff --git a/lib/domain/service/strategy/strategies/provider_strategy.dart b/lib/domain/service/strategy/strategies/provider_strategy.dart new file mode 100644 index 00000000..88e44e33 --- /dev/null +++ b/lib/domain/service/strategy/strategies/provider_strategy.dart @@ -0,0 +1,72 @@ +import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/repository/screen_repository.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/default_screen_route_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/default_screen_route_generator_params.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/domain/service/strategy/state_manager_strategy.dart'; +import 'package:onix_flutter_bricks/util/extension/output/output_message_extension.dart'; + +class ProviderStrategy implements StateManagerStrategy { + final BaseGenerationService _defaultScreenRouteGenerator; + + ProviderStrategy({ + required DefaultScreenRouteGenerator defaultScreenRouteGenerator, + }) : _defaultScreenRouteGenerator = defaultScreenRouteGenerator; + + @override + List get variants => [ + const StatefulStateManagementVariant(), + const StatelessStateManagementVariant(), + const ProviderStateManagementVariant(), + ]; + + @override + Future generate({ + required Config config, + required ScreenRepository screenRepository, + required void Function(String) logResult, + }) async { + try { + final screensNotExist = config.screens + .where( + (element) => !element.exists, + ) + .toList(); + + if (screensNotExist.isEmpty) { + await _defaultScreenRouteGenerator.generate( + DefaultScreenRouteGeneratorParams( + projectPath: config.projectPath, + projectName: config.projectName, + router: config.router, + ), + ); + } else { + for (var i = 0; i < screensNotExist.length; i++) { + final screen = screensNotExist[i]; + logResult( + 'Generating screen ${screen.name}...'.toInfoMessage(), + ); + + await screen.stateVariant.screenGenerator.generate( + ScreenGeneratorParams( + screen: screen, + projectPath: config.projectPath, + projectName: config.projectName, + router: config.router, + lastScreenItem: i == (screensNotExist.length - 1), + ), + ); + screen.exists = true; + screenRepository.modifyScreen(screen, screen.name); + } + } + } catch (e) { + logResult( + 'Error generating screens: $e'.toErrorMessage(), + ); + } + } +} diff --git a/lib/domain/service/strategy/strategies/riverpod_strategy.dart b/lib/domain/service/strategy/strategies/riverpod_strategy.dart new file mode 100644 index 00000000..3bf5adb8 --- /dev/null +++ b/lib/domain/service/strategy/strategies/riverpod_strategy.dart @@ -0,0 +1,77 @@ +import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; +import 'package:onix_flutter_bricks/domain/repository/screen_repository.dart'; +import 'package:onix_flutter_bricks/domain/service/base/base_generation_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/default_screen_route_generator.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/default_screen_route_generator_params.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; +import 'package:onix_flutter_bricks/domain/service/strategy/state_manager_strategy.dart'; +import 'package:onix_flutter_bricks/util/extension/output/output_message_extension.dart'; + +class RiverpodStrategy implements StateManagerStrategy { + final BaseGenerationService _defaultScreenRouteGenerator; + + RiverpodStrategy({ + required DefaultScreenRouteGenerator defaultScreenRouteGenerator, + }) : _defaultScreenRouteGenerator = defaultScreenRouteGenerator; + + @override + List get variants => [ + const RiverpodStatefulStateManagementVariant(), + const RiverpodStatelessStateManagementVariant(), + const StatefulStateManagementVariant(), + const StatelessStateManagementVariant(), + ]; + + @override + Future generate({ + required Config config, + required ScreenRepository screenRepository, + required void Function(String) logResult, + }) async { + try { + final screensNotExist = config.screens + .where( + (element) => !element.exists, + ) + .toList(); + + if (screensNotExist.isEmpty) { + await _defaultScreenRouteGenerator.generate( + DefaultScreenRouteGeneratorParams( + projectPath: config.projectPath, + projectName: config.projectName, + router: config.router, + ), + ); + } else { + for (var i = 0; i < screensNotExist.length; i++) { + final screen = screensNotExist[i]; + logResult( + 'Generating screen ${screen.name}...'.toInfoMessage(), + ); + + await screen.stateVariant.screenGenerator.generate( + ScreenGeneratorParams( + screen: screen, + projectPath: config.projectPath, + projectName: config.projectName, + router: config.router, + lastScreenItem: i == (screensNotExist.length - 1), + ), + ); + screen.exists = true; + screenRepository.modifyScreen(screen, screen.name); + } + } + + logResult( + 'Screens generated!'.toInfoMessage(), + ); + } catch (e) { + logResult( + 'Error generating screens: $e'.toErrorMessage(), + ); + } + } +} diff --git a/lib/domain/usecase/fastlane/generate_fastlane_files_use_case.dart b/lib/domain/usecase/fastlane/generate_fastlane_files_use_case.dart index 0f780a0f..b6d59141 100644 --- a/lib/domain/usecase/fastlane/generate_fastlane_files_use_case.dart +++ b/lib/domain/usecase/fastlane/generate_fastlane_files_use_case.dart @@ -18,7 +18,8 @@ class GenerateFastlaneFilesUseCase { }) async { if (isModify) { _outputService.add( - '{#info}Fastlane generation omitted because of the project modification', + '{#info}Fastlane generation omitted because of the project ' + 'modification', ); return; } diff --git a/lib/domain/usecase/file_generation/generate_screens_usecase.dart b/lib/domain/usecase/file_generation/generate_screens_usecase.dart index d7495fd6..b87673d4 100644 --- a/lib/domain/usecase/file_generation/generate_screens_usecase.dart +++ b/lib/domain/usecase/file_generation/generate_screens_usecase.dart @@ -1,62 +1,22 @@ import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/domain/repository/screen_repository.dart'; -import 'package:onix_flutter_bricks/domain/service/file_generator_service/file_generator_service.dart'; -import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/default_screen_route_generator_params.dart'; -import 'package:onix_flutter_bricks/domain/service/file_generator_service/screen_generators/params/screen_generator_params.dart'; import 'package:onix_flutter_bricks/domain/service/output_service/output_service.dart'; -import 'package:onix_flutter_bricks/util/extension/output/output_message_extension.dart'; class GenerateScreensUseCase { final OutputService _outputService; - final FileGeneratorService _fileGeneratorService; final ScreenRepository _screenRepository; const GenerateScreensUseCase( this._outputService, - this._fileGeneratorService, this._screenRepository, ); Future call({ required Config config, - }) async { - final screensNotExist = config.screens - .where( - (element) => !element.exists, - ) - .toList(); - - if (screensNotExist.isEmpty) { - await _fileGeneratorService.generateDefaultScreenRoute( - DefaultScreenRouteGeneratorParams( - projectPath: config.projectPath, - projectName: config.projectName, - router: config.router, - ), + }) => + config.stateManager.strategy.generate( + config: config, + screenRepository: _screenRepository, + logResult: _outputService.add, ); - } else { - for (int i = 0; i < screensNotExist.length; i++) { - final screen = screensNotExist[i]; - _outputService.add( - 'Generating screen ${screen.name}...'.toInfoMessage(), - ); - - await _fileGeneratorService.generateScreen( - ScreenGeneratorParams( - screen: screen, - projectPath: config.projectPath, - projectName: config.projectName, - router: config.router, - lastScreenItem: i == (screensNotExist.length - 1), - ), - ); - screen.exists = true; - _screenRepository.modifyScreen(screen, screen.name); - } - } - - _outputService.add( - 'Screens generated!'.toInfoMessage(), - ); - } } diff --git a/lib/domain/usecase/file_generation/generate_signing_config_usecase.dart b/lib/domain/usecase/file_generation/generate_signing_config_usecase.dart index cb887699..fbe0863c 100644 --- a/lib/domain/usecase/file_generation/generate_signing_config_usecase.dart +++ b/lib/domain/usecase/file_generation/generate_signing_config_usecase.dart @@ -1,6 +1,6 @@ -import 'package:onix_flutter_bricks/core/arch/domain/entity/result/result.dart'; -import 'package:onix_flutter_bricks/domain/service/base/params/base_generation_params.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/file_generator_service.dart'; +import 'package:onix_flutter_bricks/domain/service/file_generator_service/signing_generator/params/signing_generator_params.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; class GenerateSigningConfigUseCase { final FileGeneratorService _fileGeneratorService; @@ -9,8 +9,8 @@ class GenerateSigningConfigUseCase { this._fileGeneratorService, ); - Future> call({ - required BaseGenerationParams params, + Future> call({ + required SingingGeneratorParams params, }) async => _fileGeneratorService.generateSigning(params); } diff --git a/lib/domain/usecase/process/get_branches_process_usecase.dart b/lib/domain/usecase/process/get_branches_process_usecase.dart index a445df25..eaa72f57 100644 --- a/lib/domain/usecase/process/get_branches_process_usecase.dart +++ b/lib/domain/usecase/process/get_branches_process_usecase.dart @@ -9,7 +9,7 @@ class GetBranchesProcessUseCase { 'git', [ 'ls-remote', - 'https://github.com/Onix-Systems/onix-flutter-project-generator.git' + 'https://github.com/Onix-Systems/onix-flutter-project-generator.git', ], workingDirectory: '/', ); @@ -17,7 +17,7 @@ class GetBranchesProcessUseCase { process.stdout.transform(utf8.decoder).listen( (event) { final lines = event.split('\n'); - for (var line in lines) { + for (final line in lines) { if (line.contains('refs/heads/')) { final start = line.indexOf('refs/heads/'); final branch = line.substring(start).replaceAll('refs/heads/', ''); diff --git a/lib/domain/usecase/process/get_signing_fingerprint_usecase.dart b/lib/domain/usecase/process/get_signing_fingerprint_usecase.dart index 18dd53a7..c88e78de 100644 --- a/lib/domain/usecase/process/get_signing_fingerprint_usecase.dart +++ b/lib/domain/usecase/process/get_signing_fingerprint_usecase.dart @@ -4,15 +4,15 @@ import 'dart:io'; import 'package:onix_flutter_bricks/domain/entity/config/fingerprint.dart'; import 'package:onix_flutter_bricks/util/enum/fingerprint_type.dart'; -class GetSigningFingerprintUseCase { - final _fingerprintsKey = 'Certificate fingerprints:'; - final _sha1Key = 'SHA1:'; - final _sha256Key = 'SHA256:'; +const _fingerprintsKey = 'Certificate fingerprints:'; +const _sha1Key = 'SHA1:'; +const _sha256Key = 'SHA256:'; +class GetSigningFingerprintUseCase { const GetSigningFingerprintUseCase(); Future> call({ - required projectFolder, + required String projectFolder, required String password, }) async { final workDirectory = '$projectFolder/android/app/signing'; @@ -40,7 +40,7 @@ class GetSigningFingerprintUseCase { event.indexOf(_fingerprintsKey) + _fingerprintsKey.length; final fingerPrints = event.substring(startFingerprints); final lines = fingerPrints.split('\n'); - for (var line in lines) { + for (final line in lines) { if (line.contains(_sha1Key)) { final fingerprint = _clearFingerprint( _sha1Key, diff --git a/lib/domain/usecase/process/run_process_usecase.dart b/lib/domain/usecase/process/run_process_usecase.dart index 403590d2..c90962e2 100644 --- a/lib/domain/usecase/process/run_process_usecase.dart +++ b/lib/domain/usecase/process/run_process_usecase.dart @@ -13,7 +13,7 @@ class RunProcessUseCase { final processRunner = ProcessRunner(_outputService); await processRunner.newProcess(workingDirectory: workDir); - for (var command in commands) { + for (final command in commands) { processRunner.execCommand(command); } final exitCode = await processRunner.waitForExit(); diff --git a/lib/domain/usecase/screen/clear_screens_use_case.dart b/lib/domain/usecase/screen/clear_screens_use_case.dart new file mode 100644 index 00000000..944d5738 --- /dev/null +++ b/lib/domain/usecase/screen/clear_screens_use_case.dart @@ -0,0 +1,9 @@ +import 'package:onix_flutter_bricks/domain/repository/screen_repository.dart'; + +class ClearScreensUseCase { + final ScreenRepository _screenRepository; + + ClearScreensUseCase(this._screenRepository); + + void call() => _screenRepository.empty(); +} diff --git a/lib/domain/usecase/swagger/create_swagger_components_usecase.dart b/lib/domain/usecase/swagger/create_swagger_components_usecase.dart index 8e623e30..7db022c0 100644 --- a/lib/domain/usecase/swagger/create_swagger_components_usecase.dart +++ b/lib/domain/usecase/swagger/create_swagger_components_usecase.dart @@ -4,7 +4,8 @@ import 'package:onix_flutter_bricks/domain/service/component_generator/params/co class CreateSwaggerComponentsUseCase { final SwaggerRepository _swaggerRepository; - final BaseGenerationService _componentGenerator; + final BaseGenerationService + _componentGenerator; const CreateSwaggerComponentsUseCase( this._swaggerRepository, @@ -19,7 +20,7 @@ class CreateSwaggerComponentsUseCase { if (components == null) { return 'Invalid Data Components'; } - _componentGenerator.generate( + await _componentGenerator.generate( ComponentGeneratorParams( projectName: projectName, projectPath: projectPath, diff --git a/lib/domain/usecase/swagger/empty_swagger_components_usecase.dart b/lib/domain/usecase/swagger/empty_swagger_components_usecase.dart new file mode 100644 index 00000000..6471869d --- /dev/null +++ b/lib/domain/usecase/swagger/empty_swagger_components_usecase.dart @@ -0,0 +1,9 @@ +import 'package:onix_flutter_bricks/domain/repository/swagger_repository.dart'; + +class ClearSwaggerComponentsUseCase { + final SwaggerRepository _swaggerRepository; + + const ClearSwaggerComponentsUseCase(this._swaggerRepository); + + void call() => _swaggerRepository.clearComponents(); +} diff --git a/lib/domain/usecase/swagger/fetch_swagger_data_usecase.dart b/lib/domain/usecase/swagger/fetch_swagger_data_usecase.dart index db7a0a39..98867398 100644 --- a/lib/domain/usecase/swagger/fetch_swagger_data_usecase.dart +++ b/lib/domain/usecase/swagger/fetch_swagger_data_usecase.dart @@ -1,6 +1,6 @@ -import 'package:onix_flutter_bricks/core/arch/domain/entity/result/result.dart'; import 'package:onix_flutter_bricks/domain/entity/component/components.dart'; import 'package:onix_flutter_bricks/domain/repository/swagger_repository.dart'; +import 'package:onix_flutter_core/onix_flutter_core.dart'; class FetchSwaggerDataUseCase { final SwaggerRepository _swaggerRepository; diff --git a/lib/main.dart b/lib/main.dart index deedbde1..b22eb661 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -6,9 +6,9 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; import 'package:onix_flutter_bricks/app/app.dart'; -import 'package:onix_flutter_bricks/core/app/app_initialization.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/app_bloc_observer.dart'; +import 'package:onix_flutter_bricks/app/app_initialization.dart'; import 'package:window_manager/window_manager.dart'; Future main() async { @@ -20,7 +20,7 @@ Future main() async { await windowManager.ensureInitialized(); - WindowOptions windowOptions = const WindowOptions( + const windowOptions = WindowOptions( minimumSize: Size(1100, 750), size: Size(1100, 750), center: true, @@ -38,18 +38,16 @@ Future main() async { runApp(const App()); }, - (error, stackTrace) { - if (kDebugMode) { - print('runZonedGuarded: Caught error in root zone.\n$error'); - print(stackTrace); - } - //there we can add FirebaseCrashlytics recordError method - }, - )?.catchError((e, trace) { - if (kDebugMode) { - print('ERROR: $e'); - print(trace); - } + _onError, + )?.catchError((error, stackTrace) { + _onError(error, stackTrace); exit(-1); }); } + +void _onError(dynamic error, dynamic stackTrace) { + if (kDebugMode) { + print('ERROR: $error'); + print(stackTrace); + } +} diff --git a/lib/presentation/screen/data_components_screen_v2/bloc/data_components_screen_v2_bloc.dart b/lib/presentation/screen/data_components_screen_v2/bloc/data_components_screen_v2_bloc.dart index 66896b73..3ef12e1c 100644 --- a/lib/presentation/screen/data_components_screen_v2/bloc/data_components_screen_v2_bloc.dart +++ b/lib/presentation/screen/data_components_screen_v2/bloc/data_components_screen_v2_bloc.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/domain/usecase/swagger/get_swagger_components_usecase.dart'; import 'package:onix_flutter_bricks/presentation/screen/data_components_screen_v2/bloc/data_components_screen_v2_bloc_imports.dart'; @@ -15,7 +15,7 @@ class DataComponentsScreenV2Bloc extends BaseBloc(_onInit); } - FutureOr _onInit( + Future _onInit( DataComponentsScreenV2IInit event, Emitter emit, ) async { diff --git a/lib/presentation/screen/data_components_screen_v2/data_components_screen_v2.dart b/lib/presentation/screen/data_components_screen_v2/data_components_screen_v2.dart index cb49ac87..cf8fe582 100644 --- a/lib/presentation/screen/data_components_screen_v2/data_components_screen_v2.dart +++ b/lib/presentation/screen/data_components_screen_v2/data_components_screen_v2.dart @@ -1,10 +1,11 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_block_state.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/presentation/screen/data_components_screen_v2/bloc/data_components_screen_v2_bloc_imports.dart'; import 'package:onix_flutter_bricks/presentation/screen/data_components_screen_v2/widget/data_components_content.dart'; @@ -35,6 +36,10 @@ class _DataComponentsScreenState extends BaseState< DataComponentsScreenV2SR, DataComponentsScreenV2> { @override + DataComponentsScreenV2Bloc createBloc() => + GetIt.I.get(); + + @override void onBlocCreated(BuildContext context, DataComponentsScreenV2Bloc bloc) { bloc.add(DataComponentsScreenV2Event.init(config: widget.config)); super.onBlocCreated(context, bloc); @@ -42,68 +47,64 @@ class _DataComponentsScreenState extends BaseState< @override Widget buildWidget(BuildContext context) { - return srObserver( - context: context, - child: CupertinoPageScaffold( - navigationBar: TitleBar(title: S.of(context).dataComponents), - child: blocBuilder( - builder: (context, state) { - final components = state.components; - return Padding( - padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16), - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - mainAxisSize: MainAxisSize.max, - children: [ - if (components == null) ...[ - const Delimiter.height(100), - Material( - color: Colors.transparent, - child: Text( - S.of(context).noDataComponents, - style: const TextStyle(fontSize: 22), - ), + return CupertinoPageScaffold( + navigationBar: TitleBar(title: S.of(context).dataComponents), + child: blocBuilder( + builder: (context, state) { + final components = state.components; + return Padding( + padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16), + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + if (components == null) ...[ + const Delimiter.height(100), + Material( + color: Colors.transparent, + child: Text( + S.of(context).noDataComponents, + style: const TextStyle(fontSize: 22), ), - ] else - Expanded( - child: Container( - padding: const EdgeInsets.all(10), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(10), - border: Border.all( - color: context.appColors.controlColor, - ), + ), + ] else + Expanded( + child: Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: context.appColors.controlColor, ), - child: Material( - color: Colors.transparent, - child: DataComponentsContent( - components: components, - ), + ), + child: Material( + color: Colors.transparent, + child: DataComponentsContent( + components: components, ), ), ), - const Delimiter.height(10), - NavigationButtonBar( - nextText: S.of(context).continueLabel, - prevText: S.of(context).goBack, - onNextPressed: () { - _onContinue(context, state); - }, - onPrevPressed: () { - _onBack(context, state); - }, ), - ], - ), - ); - }, - ), + const Delimiter.height(10), + NavigationButtonBar( + nextText: S.of(context).continueLabel, + prevText: S.of(context).goBack, + onNextPressed: () { + _onContinue(context, state); + }, + onPrevPressed: () { + _onBack(context, state); + }, + ), + ], + ), + ); + }, ), - onSR: _onSingleResult, ); } - void _onSingleResult( + @override + void onSR( BuildContext context, DataComponentsScreenV2SR singleResult, ) { diff --git a/lib/presentation/screen/data_components_screen_v2/widget/data_components_content.dart b/lib/presentation/screen/data_components_screen_v2/widget/data_components_content.dart index 6aa9a38f..1bfe032e 100644 --- a/lib/presentation/screen/data_components_screen_v2/widget/data_components_content.dart +++ b/lib/presentation/screen/data_components_screen_v2/widget/data_components_content.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/component/components.dart'; import 'package:onix_flutter_bricks/presentation/screen/data_components_screen_v2/widget/objects/object_item.dart'; import 'package:onix_flutter_bricks/presentation/screen/data_components_screen_v2/widget/section_header.dart'; @@ -45,34 +45,3 @@ class _DataComponentsContentState extends State { ); } } - -// ListView( -// padding: EdgeInsets.zero, -// children: [ -// const SectionHeader( -// title: 'Sources', -// ), -// Column( -// children: components.sources -// .map( -// (e) => SourceItem( -// source: e, -// ), -// ) -// .toList(), -// ), -// const SizedBox(height: 32), -// const SectionHeader( -// title: 'Objects', -// ), -// Column( -// children: components.dataObjects -// .map( -// (e) => ObjectItem( -// object: e, -// ), -// ) -// .toList(), -// ), -// ], -// ); diff --git a/lib/presentation/screen/data_components_screen_v2/widget/input_params/form_data.dart b/lib/presentation/screen/data_components_screen_v2/widget/input_params/form_data.dart index 93165c61..4a181520 100644 --- a/lib/presentation/screen/data_components_screen_v2/widget/input_params/form_data.dart +++ b/lib/presentation/screen/data_components_screen_v2/widget/input_params/form_data.dart @@ -28,13 +28,15 @@ class FormData extends StatelessWidget { ), ), const SizedBox(height: 4), - ...formData.map((e) => Text( - '${e.type.getTypeDeclaration(DataFileType.none)} ${e.name}', - style: TextStyle( - color: context.appColors.textColor, - fontSize: 14, - ), - )), + ...formData.map( + (e) => Text( + '${e.type.getTypeDeclaration(DataFileType.none)} ${e.name}', + style: TextStyle( + color: context.appColors.textColor, + fontSize: 14, + ), + ), + ), ], ); } diff --git a/lib/presentation/screen/data_components_screen_v2/widget/input_params/input_body.dart b/lib/presentation/screen/data_components_screen_v2/widget/input_params/input_body.dart index 33e28236..48773694 100644 --- a/lib/presentation/screen/data_components_screen_v2/widget/input_params/input_body.dart +++ b/lib/presentation/screen/data_components_screen_v2/widget/input_params/input_body.dart @@ -30,7 +30,8 @@ class InputBody extends StatelessWidget { ), const SizedBox(height: 4), Text( - '${bodyNotNull.type.getTypeDeclaration(DataFileType.none)} ${bodyNotNull.name}', + '${bodyNotNull.type.getTypeDeclaration(DataFileType.none)} ' + '${bodyNotNull.name}', style: TextStyle( color: context.appColors.textColor, fontSize: 14, diff --git a/lib/presentation/screen/data_components_screen_v2/widget/input_params/path_params.dart b/lib/presentation/screen/data_components_screen_v2/widget/input_params/path_params.dart index 0c49bb04..ddc7aae4 100644 --- a/lib/presentation/screen/data_components_screen_v2/widget/input_params/path_params.dart +++ b/lib/presentation/screen/data_components_screen_v2/widget/input_params/path_params.dart @@ -28,13 +28,15 @@ class PathParams extends StatelessWidget { ), ), const SizedBox(height: 4), - ...pathParams.map((e) => Text( - '${e.type.getTypeDeclaration(DataFileType.none)} ${e.name}', - style: TextStyle( - color: context.appColors.textColor, - fontSize: 14, - ), - )), + ...pathParams.map( + (e) => Text( + '${e.type.getTypeDeclaration(DataFileType.none)} ${e.name}', + style: TextStyle( + color: context.appColors.textColor, + fontSize: 14, + ), + ), + ), ], ); } diff --git a/lib/presentation/screen/data_components_screen_v2/widget/input_params/query_params.dart b/lib/presentation/screen/data_components_screen_v2/widget/input_params/query_params.dart index 1ecdd337..daa7fff2 100644 --- a/lib/presentation/screen/data_components_screen_v2/widget/input_params/query_params.dart +++ b/lib/presentation/screen/data_components_screen_v2/widget/input_params/query_params.dart @@ -28,13 +28,15 @@ class QueryParams extends StatelessWidget { ), ), const SizedBox(height: 4), - ...queryParams.map((e) => Text( - '${e.type.getTypeDeclaration(DataFileType.none)} ${e.name}', - style: TextStyle( - color: context.appColors.textColor, - fontSize: 14, - ), - )), + ...queryParams.map( + (e) => Text( + '${e.type.getTypeDeclaration(DataFileType.none)} ${e.name}', + style: TextStyle( + color: context.appColors.textColor, + fontSize: 14, + ), + ), + ), ], ); } diff --git a/lib/presentation/screen/data_components_screen_v2/widget/objects/object_item.dart b/lib/presentation/screen/data_components_screen_v2/widget/objects/object_item.dart index b82c9050..ac2bd7bd 100644 --- a/lib/presentation/screen/data_components_screen_v2/widget/objects/object_item.dart +++ b/lib/presentation/screen/data_components_screen_v2/widget/objects/object_item.dart @@ -16,7 +16,7 @@ class ObjectItem extends StatelessWidget { @override Widget build(BuildContext context) { - return Container( + return ColoredBox( color: context.appColors.contrastColor, child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -24,11 +24,13 @@ class ObjectItem extends StatelessWidget { const SizedBox(height: 8), Padding( padding: const EdgeInsets.symmetric(horizontal: 16), - child: Text(object.name.titleCase, - style: TextStyle( - color: context.appColors.textColor, - fontSize: 16, - )), + child: Text( + object.name.titleCase, + style: TextStyle( + color: context.appColors.textColor, + fontSize: 16, + ), + ), ), const SizedBox(height: 8), Container( @@ -39,12 +41,12 @@ class ObjectItem extends StatelessWidget { vertical: 8, ), child: Column( - mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: object.variables .map( - (e) => Text( - '${e.type.getTypeDeclaration(DataFileType.none)} ${e.name.camelCase}'), + (e) => + Text('${e.type.getTypeDeclaration(DataFileType.none)} ' + '${e.name.camelCase}'), ) .toList(), ), diff --git a/lib/presentation/screen/data_components_screen_v2/widget/sources/request_item.dart b/lib/presentation/screen/data_components_screen_v2/widget/sources/request_item.dart index 840ac4ff..f74e1031 100644 --- a/lib/presentation/screen/data_components_screen_v2/widget/sources/request_item.dart +++ b/lib/presentation/screen/data_components_screen_v2/widget/sources/request_item.dart @@ -18,7 +18,7 @@ class RequestItem extends StatelessWidget { @override Widget build(BuildContext context) { - return Container( + return ColoredBox( color: context.appColors.contrastColor, child: Column( children: [ @@ -26,14 +26,14 @@ class RequestItem extends StatelessWidget { Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: Row( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.center, children: [ - Text(request.operationId, - style: TextStyle( - color: context.appColors.textColor, - fontSize: 16, - )), + Text( + request.operationId, + style: TextStyle( + color: context.appColors.textColor, + fontSize: 16, + ), + ), const SizedBox(width: 16), Text( '(${request.path})', @@ -46,7 +46,7 @@ class RequestItem extends StatelessWidget { ), ), const SizedBox(height: 8), - Container( + ColoredBox( color: context.appColors.darkContrastColor, child: Column( children: [ diff --git a/lib/presentation/screen/figma_styles_screen/bloc/figma_styles_screen_bloc.dart b/lib/presentation/screen/figma_styles_screen/bloc/figma_styles_screen_bloc.dart index b60f7e41..a4f62e18 100644 --- a/lib/presentation/screen/figma_styles_screen/bloc/figma_styles_screen_bloc.dart +++ b/lib/presentation/screen/figma_styles_screen/bloc/figma_styles_screen_bloc.dart @@ -1,8 +1,8 @@ import 'dart:async'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/domain/usecase/styles/get_figma_styles_usecase.dart'; import 'package:onix_flutter_bricks/presentation/screen/figma_styles_screen/bloc/figma_styles_screen_bloc_imports.dart'; @@ -18,28 +18,32 @@ class FigmaStylesScreenBloc extends BaseBloc(_onClear); } - FutureOr _onInit( + void _onInit( FigmaStylesScreenEventInit event, Emitter emit, ) { - emit(state.copyWith( - config: event.config, - )); + emit( + state.copyWith( + config: event.config, + ), + ); } - FutureOr _onGetStyles( + Future _onGetStyles( FigmaStylesScreenEventOnGetStyles event, Emitter emit, ) async { if (event.figmaId.isEmpty) { - addSr(FigmaStylesScreenSR.error( - error: S.current.figmaGetStylesEmptyFileId)); + addSr( + FigmaStylesScreenSR.error(error: S.current.figmaGetStylesEmptyFileId), + ); return; } if (event.token.isEmpty) { addSr( - FigmaStylesScreenSR.error(error: S.current.figmaGetStylesEmptyToken)); + FigmaStylesScreenSR.error(error: S.current.figmaGetStylesEmptyToken), + ); return; } @@ -61,11 +65,13 @@ class FigmaStylesScreenBloc extends BaseBloc _onClear( + void _onClear( FigmaStylesScreenEventOnClear event, Emitter emit, ) { - emit(state.copyWith( - config: state.config.copyWith( - styles: [], + emit( + state.copyWith( + config: state.config.copyWith( + styles: [], + ), ), - )); + ); } } diff --git a/lib/presentation/screen/figma_styles_screen/figma_styles_screen.dart b/lib/presentation/screen/figma_styles_screen/figma_styles_screen.dart index 20dccc50..8fdd066d 100644 --- a/lib/presentation/screen/figma_styles_screen/figma_styles_screen.dart +++ b/lib/presentation/screen/figma_styles_screen/figma_styles_screen.dart @@ -1,10 +1,11 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_block_state.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_styles.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/presentation/screen/figma_styles_screen/bloc/figma_styles_screen_bloc_imports.dart'; @@ -20,9 +21,9 @@ class FigmaStylesScreen extends StatefulWidget { final Config config; const FigmaStylesScreen({ + required this.config, this.onContinue, this.onBack, - required this.config, super.key, }); @@ -35,6 +36,9 @@ class _FigmaStylesScreenState extends BaseState GetIt.I.get(); + @override Widget buildWidget(BuildContext context) { return CupertinoPageScaffold( @@ -42,8 +46,8 @@ class _FigmaStylesScreenState extends BaseState _buildMainContainer(context, state), + child: blocBuilder( + builder: (_, state) => _buildMainContainer(context, state), ), ), ); @@ -118,7 +122,6 @@ class _FigmaStylesScreenState extends BaseState blocOf(context) .add(const FigmaStylesScreenEventOnClear()), diff --git a/lib/presentation/screen/figma_styles_screen/widgets/styles_widget.dart b/lib/presentation/screen/figma_styles_screen/widgets/styles_widget.dart index e3b9fc42..9259a55b 100644 --- a/lib/presentation/screen/figma_styles_screen/widgets/styles_widget.dart +++ b/lib/presentation/screen/figma_styles_screen/widgets/styles_widget.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_color_style.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_styles.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_text_style.dart'; @@ -67,7 +67,9 @@ class StylesWidget extends StatelessWidget { decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), border: Border.all( - color: context.appColors.alarmColor, width: 2), + color: context.appColors.alarmColor, + width: 2, + ), ), child: Column( children: [ @@ -131,7 +133,9 @@ class StylesWidget extends StatelessWidget { decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), border: Border.all( - color: context.appColors.alarmColor, width: 2), + color: context.appColors.alarmColor, + width: 2, + ), ), child: Column( children: [ @@ -163,7 +167,7 @@ class StylesWidget extends StatelessWidget { ), ), ), - const SliverToBoxAdapter(child: Delimiter.height(20)) + const SliverToBoxAdapter(child: Delimiter.height(20)), ], ), ), diff --git a/lib/presentation/screen/figma_styles_screen/widgets/text_style_item.dart b/lib/presentation/screen/figma_styles_screen/widgets/text_style_item.dart index 6f1ea3b7..dd7a83d3 100644 --- a/lib/presentation/screen/figma_styles_screen/widgets/text_style_item.dart +++ b/lib/presentation/screen/figma_styles_screen/widgets/text_style_item.dart @@ -16,7 +16,7 @@ class TextStyleItem extends StatelessWidget { color: context.appColors.fadedColor, ), child: Padding( - padding: const EdgeInsets.all(8.0), + padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ diff --git a/lib/presentation/screen/generation_screen/bloc/generation_screen_bloc.dart b/lib/presentation/screen/generation_screen/bloc/generation_screen_bloc.dart index b724381f..bb604026 100644 --- a/lib/presentation/screen/generation_screen/bloc/generation_screen_bloc.dart +++ b/lib/presentation/screen/generation_screen/bloc/generation_screen_bloc.dart @@ -2,7 +2,7 @@ import 'dart:async'; import 'dart:io'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; import 'package:onix_flutter_bricks/core/di/repository.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/domain/service/docs_service/params/docs_generation_params.dart'; @@ -66,7 +66,7 @@ class GenerationScreenBloc extends BaseBloc(_openProject); } - FutureOr _onInit( + Future _onInit( GenerationScreenEventInit event, Emitter emit, ) async { @@ -81,7 +81,7 @@ class GenerationScreenBloc extends BaseBloc _onGenerateProject( + Future _onGenerateProject( GenerationScreenEventGenerateProject event, Emitter emit, ) async { @@ -89,13 +89,13 @@ class GenerationScreenBloc extends BaseBloc - var flavors = state.config.getFlavorsAsSet(); + final flavors = state.config.getFlavorsAsSet(); ///create config file, clear old possible copy - var configFile = File('${state.config.projectPath}/config.json'); + final configFile = File('${state.config.projectPath}/config.json'); if (configFile.existsSync()) { configFile.deleteSync(); } @@ -149,16 +149,16 @@ class GenerationScreenBloc extends BaseBloc '-').join('').toInfoMessage(), + message: List.generate(10, (index) => '-').join().toInfoMessage(), ); _addOutputMessageUseCase( message: 'Project generation completed.'.toInfoMessage(), @@ -245,20 +248,22 @@ class GenerationScreenBloc extends BaseBloc '-').join('').toInfoMessage(), + message: List.generate(10, (index) => '-').join().toInfoMessage(), ); ///finish generation - emit(state.copyWith( - generatingState: GeneratingState.waiting, - config: state.config.copyWith( - screens: screenRepository.screens, + emit( + state.copyWith( + generatingState: GeneratingState.waiting, + config: state.config.copyWith( + screens: screenRepository.screens, + ), ), - )); + ); } ///when user tap on "Open Android Studio" - FutureOr _openProject( + Future _openProject( GenerationScreenEventOpenProject event, Emitter emit, ) async { diff --git a/lib/presentation/screen/generation_screen/generation_screen.dart b/lib/presentation/screen/generation_screen/generation_screen.dart index 9a55da18..5168c661 100644 --- a/lib/presentation/screen/generation_screen/generation_screen.dart +++ b/lib/presentation/screen/generation_screen/generation_screen.dart @@ -1,5 +1,6 @@ import 'package:flutter/cupertino.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_block_state.dart'; +import 'package:get_it/get_it.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/presentation/screen/generation_screen/bloc/generation_screen_bloc_imports.dart'; import 'package:onix_flutter_bricks/presentation/screen/generation_screen/widget/generation_controls.dart'; @@ -21,12 +22,15 @@ class GenerationScreen extends StatefulWidget { class _GenerationScreenState extends BaseState { + @override + GenerationScreenBloc createBloc() => GetIt.I.get(); + @override Widget buildWidget(BuildContext context) { return CupertinoPageScaffold( child: SizedBox.expand( - child: blocConsumer( - stateListener: (state) => _buildMainContainer(context, state), + child: blocBuilder( + builder: (_, state) => _buildMainContainer(context, state), ), ), ); @@ -53,7 +57,6 @@ class _GenerationScreenState extends BaseState { + @override + PlatformsScreenBloc createBloc() => PlatformsScreenBloc(); + @override void onBlocCreated(BuildContext context, PlatformsScreenBloc bloc) { bloc.add(PlatformsScreenEvent.init(config: widget.config)); diff --git a/lib/presentation/screen/platforms_screen/widgets/platform_checkbox.dart b/lib/presentation/screen/platforms_screen/widgets/platform_checkbox.dart index 0d60dd7d..9d2a5762 100644 --- a/lib/presentation/screen/platforms_screen/widgets/platform_checkbox.dart +++ b/lib/presentation/screen/platforms_screen/widgets/platform_checkbox.dart @@ -24,14 +24,13 @@ class PlatformCheckbox extends StatelessWidget { return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, children: [ Material( color: Colors.transparent, borderRadius: BorderRadius.circular(20), clipBehavior: Clip.antiAlias, child: InkWell( - onTap: () => onAction(), + onTap: onAction, child: Container( height: 100, width: 100, @@ -56,7 +55,7 @@ class PlatformCheckbox extends StatelessWidget { LabeledCheckbox( label: label, initialValue: initialValue, - onAction: () => onAction(), + onAction: onAction, ), ], ); diff --git a/lib/presentation/screen/platforms_screen/widgets/platform_screen_body.dart b/lib/presentation/screen/platforms_screen/widgets/platform_screen_body.dart index 5922a89c..8493e90e 100644 --- a/lib/presentation/screen/platforms_screen/widgets/platform_screen_body.dart +++ b/lib/presentation/screen/platforms_screen/widgets/platform_screen_body.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/presentation/screen/platforms_screen/bloc/platforms_screen_bloc_imports.dart'; import 'package:onix_flutter_bricks/presentation/screen/platforms_screen/widgets/platform_checkbox.dart'; @@ -22,10 +22,9 @@ class PlatformScreenBody extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.all(16), child: Column( mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, children: [ const Spacer(), GridView.builder( @@ -36,7 +35,6 @@ class PlatformScreenBody extends StatelessWidget { crossAxisCount: 3, mainAxisSpacing: 40, mainAxisExtent: 150, - childAspectRatio: 1, ), itemBuilder: (context, index) { final platform = AvailablePlatforms.values[index]; @@ -66,11 +64,10 @@ class PlatformScreenBody extends StatelessWidget { extra: config.copyWith( platformsList: config.platformsList, flavorize: - config.platformsList.webOnly ? false : config.flavorize, + !config.platformsList.webOnly && config.flavorize, flavors: config.platformsList.webOnly ? '' : config.flavors, - generateSigningKey: config.platformsList.webOnly - ? false - : config.generateSigningKey, + generateSigningKey: !config.platformsList.webOnly && + config.generateSigningKey, ), ); }, diff --git a/lib/presentation/screen/procedure_selection_screen/bloc/procedure_selection_screen_bloc.dart b/lib/presentation/screen/procedure_selection_screen/bloc/procedure_selection_screen_bloc.dart index 1e6546a0..01d97831 100644 --- a/lib/presentation/screen/procedure_selection_screen/bloc/procedure_selection_screen_bloc.dart +++ b/lib/presentation/screen/procedure_selection_screen/bloc/procedure_selection_screen_bloc.dart @@ -3,14 +3,16 @@ import 'dart:ui'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:intl/intl.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; import 'package:onix_flutter_bricks/core/di/repository.dart'; import 'package:onix_flutter_bricks/core/di/source.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/domain/service/file_generator_service/signing_generator/params/signing_generator_params.dart'; import 'package:onix_flutter_bricks/domain/usecase/file_generation/generate_signing_config_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/process/get_signing_fingerprint_usecase.dart'; +import 'package:onix_flutter_bricks/domain/usecase/screen/clear_screens_use_case.dart'; +import 'package:onix_flutter_bricks/domain/usecase/swagger/empty_swagger_components_usecase.dart'; import 'package:onix_flutter_bricks/presentation/screen/procedure_selection_screen/bloc/procedure_selection_screen_bloc_imports.dart'; import 'package:onix_flutter_bricks/util/extension/project_config_extension.dart'; @@ -20,11 +22,15 @@ class ProcedureSelectionScreenBloc extends BaseBloc< ProcedureSelectionScreenSR> { final GenerateSigningConfigUseCase _generateSigningConfigUseCase; final GetSigningFingerprintUseCase _getSigningFingerprintUseCase; + final ClearSwaggerComponentsUseCase _clearSwaggerComponentsUseCase; + final ClearScreensUseCase _clearScreensUseCase; ProcedureSelectionScreenBloc( - this._generateSigningConfigUseCase, - this._getSigningFingerprintUseCase, - ) : super(const ProcedureSelectionScreenStateData(config: Config())) { + this._generateSigningConfigUseCase, + this._getSigningFingerprintUseCase, + this._clearSwaggerComponentsUseCase, + this._clearScreensUseCase) + : super(const ProcedureSelectionScreenStateData(config: Config())) { on(_onInit); on(_onProjectOpen); on(_onNewProject); @@ -32,39 +38,45 @@ class ProcedureSelectionScreenBloc extends BaseBloc< on(_onnAndroidSigning); } - FutureOr _onInit( + void _onInit( ProcedureSelectionScreenEventInit event, Emitter emit, ) { - emit(state.copyWith( - config: event.config, - language: Intl.getCurrentLocale(), - )); + emit( + state.copyWith( + config: event.config, + language: Intl.getCurrentLocale(), + ), + ); } - FutureOr _onNewProject( + Future _onNewProject( ProcedureSelectionScreenEventOnNewProject event, Emitter emit, ) async { - screenRepository.empty(); - - emit(state.copyWith( - config: Config( - projectPath: event.projectPath, - localVersion: state.config.localVersion, - remoteVersion: state.config.remoteVersion, + _clearScreensUseCase(); + _clearSwaggerComponentsUseCase(); + + emit( + state.copyWith( + config: Config( + projectPath: event.projectPath, + localVersion: state.config.localVersion, + remoteVersion: state.config.remoteVersion, + ), ), - )); + ); addSr(const ProcedureSelectionScreenSR.onNewProject()); } - FutureOr _onProjectOpen( + Future _onProjectOpen( ProcedureSelectionScreenEventOnProjectOpen event, Emitter emit, ) async { final config = await configSource.getConfig( - configPath: '${event.projectURI}/.gen_config.json'); + configPath: '${event.projectURI}/.gen_config.json', + ); if (config == Config.empty()) { addSr(const ProcedureSelectionScreenSR.emptyConfig()); @@ -74,31 +86,36 @@ class ProcedureSelectionScreenBloc extends BaseBloc< final projectName = event.projectURI.split('/').last; final projectPath = event.projectURI.replaceAll('/$projectName', ''); - screenRepository.empty(); - screenRepository.addAll(screens: config.screens); - - emit(state.copyWith( - config: config.copyWith( - projectName: projectName, - projectPath: projectPath, - projectExists: true, - localVersion: state.config.localVersion, - remoteVersion: state.config.remoteVersion, + screenRepository + ..empty() + ..addAll(screens: config.screens); + + emit( + state.copyWith( + config: config.copyWith( + projectName: projectName, + projectPath: projectPath, + projectExists: true, + localVersion: state.config.localVersion, + remoteVersion: state.config.remoteVersion, + ), ), - )); + ); addSr(const ProcedureSelectionScreenSR.loadFinished()); } - FutureOr _onLocaleChange( + Future _onLocaleChange( ProcedureSelectionScreenEventOnLocaleChange event, Emitter emit, ) async { - S.load(Locale(event.language)); + await S.load(Locale(event.language)); - emit(state.copyWith( - language: event.language, - )); + emit( + state.copyWith( + language: event.language, + ), + ); } FutureOr _onnAndroidSigning( @@ -106,7 +123,7 @@ class ProcedureSelectionScreenBloc extends BaseBloc< Emitter emit, ) async { showProgress(); - String signingPassword = state.config.getSigningPassword( + final signingPassword = state.config.getSigningPassword( ignoreSetting: true, ); @@ -118,7 +135,7 @@ class ProcedureSelectionScreenBloc extends BaseBloc< separateFromBrick: true, ), ); - hideProgress(); + await hideProgress(); if (result.success) { final fingerprints = await _getSigningFingerprintUseCase( projectFolder: event.directory.path, diff --git a/lib/presentation/screen/procedure_selection_screen/procedure_selection_screen.dart b/lib/presentation/screen/procedure_selection_screen/procedure_selection_screen.dart index f786e1b1..87c1e1e1 100644 --- a/lib/presentation/screen/procedure_selection_screen/procedure_selection_screen.dart +++ b/lib/presentation/screen/procedure_selection_screen/procedure_selection_screen.dart @@ -3,12 +3,13 @@ import 'dart:io'; import 'package:file_selector/file_selector.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_block_state.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/domain/entity/failure/signing_failure.dart'; import 'package:onix_flutter_bricks/presentation/screen/procedure_selection_screen/bloc/procedure_selection_screen_bloc_imports.dart'; @@ -22,6 +23,7 @@ import 'package:onix_flutter_bricks/presentation/widget/title_bar.dart'; import 'package:onix_flutter_bricks/util/enum/tool_type.dart'; import 'package:onix_flutter_bricks/util/extension/directory_extension.dart'; import 'package:onix_flutter_bricks/util/extension/failure_dialog_extension.dart'; +import 'package:onix_flutter_core_models/onix_flutter_core_models.dart'; class ProcedureSelectionScreen extends StatefulWidget { final Config config; @@ -41,11 +43,20 @@ class _ProcedureSelectionScreenState extends BaseState< ProcedureSelectionScreenBloc, ProcedureSelectionScreenSR, ProcedureSelectionScreen> { + @override + ProcedureSelectionScreenBloc createBloc() => + GetIt.I.get(); + + @override + void onBlocCreated(BuildContext context, ProcedureSelectionScreenBloc bloc) { + bloc.add(ProcedureSelectionScreenEventInit(config: widget.config)); + super.onBlocCreated(context, bloc); + } + @override Widget buildWidget(BuildContext context) { - return srObserver( - context: context, - child: blocBuilder(builder: (context, state) { + return blocBuilder( + builder: (context, state) { return CupertinoPageScaffold( navigationBar: TitleBar( title: S.of(context).selectProjectFolder, @@ -64,7 +75,8 @@ class _ProcedureSelectionScreenState extends BaseState< onValueChanged: (value) { blocOf(context).add( ProcedureSelectionScreenEventOnLocaleChange( - language: value), + language: value, + ), ); }, ), @@ -76,30 +88,22 @@ class _ProcedureSelectionScreenState extends BaseState< switch (value) { case ToolType.generateAndroidSigning: _onGenerateSigningSelected(context); - break; } }, - ) + ), ], ), child: SizedBox.expand(child: _buildMainContainer(context, state)), ); - }), - onSR: _onSingleResult, + }, ); } @override - void onBlocCreated(BuildContext context, ProcedureSelectionScreenBloc bloc) { - bloc.failureStream.listen( - (failure) { - if (failure is SigningFailure) { - context.onSigningFailure(failure); - } - }, - ); - bloc.add(ProcedureSelectionScreenEventInit(config: widget.config)); - super.onBlocCreated(context, bloc); + void onFailure(BuildContext context, Failure failure) { + if (failure is SigningFailure) { + context.onSigningFailure(failure); + } } Widget _buildMainContainer( @@ -121,11 +125,13 @@ class _ProcedureSelectionScreenState extends BaseState< onPressed: () { getDirectoryPath().then( (value) { + if (!context.mounted) return; if (value != null) { - blocOf(context) - .add(ProcedureSelectionScreenEventOnNewProject( - projectPath: value, - )); + blocOf(context).add( + ProcedureSelectionScreenEventOnNewProject( + projectPath: value, + ), + ); } else { Dialogs.showOkDialog( context: context, @@ -155,7 +161,8 @@ class _ProcedureSelectionScreenState extends BaseState< child: Text( (state.config.localVersion.isNotEmpty && state.config.remoteVersion.isNotEmpty) - ? 'v${state.config.localVersion} (Remote: v${state.config.remoteVersion})' + ? 'v${state.config.localVersion} ' + '(Remote: v${state.config.remoteVersion})' : '', style: context.appTextStyles.fs18?.copyWith( decoration: TextDecoration.none, @@ -167,11 +174,12 @@ class _ProcedureSelectionScreenState extends BaseState< ); } - void _onSingleResult( - BuildContext context, ProcedureSelectionScreenSR singleResult) { - singleResult.when( - //TODO Resolve - loadFinished: () {}, + @override + void onSR( + BuildContext context, + ProcedureSelectionScreenSR singleResult, + ) { + singleResult.whenOrNull( emptyConfig: () => Dialogs.showOkDialog( context: context, isError: true, @@ -202,19 +210,21 @@ class _ProcedureSelectionScreenState extends BaseState< } Map _mapValues(BuildContext context) { - Map result = {}; - for (String value + final result = {}; + for (final value in S.delegate.supportedLocales.map((e) => e.languageCode)) { - result.addAll({ - value: Text( - value.toUpperCase(), - style: context.appTextStyles.fs18?.copyWith( - color: blocOf(context).state.language == value - ? context.appColors.darkColor - : context.appColors.fadedColor, + result.addAll( + { + value: Text( + value.toUpperCase(), + style: context.appTextStyles.fs18?.copyWith( + color: blocOf(context).state.language == value + ? context.appColors.darkColor + : context.appColors.fadedColor, + ), ), - ) - }); + }, + ); } return result; } diff --git a/lib/presentation/screen/procedure_selection_screen/widget/fingerprint_dialog_body.dart b/lib/presentation/screen/procedure_selection_screen/widget/fingerprint_dialog_body.dart index f76eeab3..c2091b98 100644 --- a/lib/presentation/screen/procedure_selection_screen/widget/fingerprint_dialog_body.dart +++ b/lib/presentation/screen/procedure_selection_screen/widget/fingerprint_dialog_body.dart @@ -1,8 +1,8 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/config/fingerprint.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; diff --git a/lib/presentation/screen/procedure_selection_screen/widget/tools_popup_button.dart b/lib/presentation/screen/procedure_selection_screen/widget/tools_popup_button.dart index 208fca84..3a0586a9 100644 --- a/lib/presentation/screen/procedure_selection_screen/widget/tools_popup_button.dart +++ b/lib/presentation/screen/procedure_selection_screen/widget/tools_popup_button.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; import 'package:onix_flutter_bricks/util/enum/tool_type.dart'; class ToolsPopupButton extends StatelessWidget { @@ -15,7 +15,7 @@ class ToolsPopupButton extends StatelessWidget { return PopupMenuButton( onSelected: onSelected, tooltip: S.of(context).tools, - itemBuilder: (BuildContext context) => >[ + itemBuilder: (context) => >[ PopupMenuItem( value: ToolType.generateAndroidSigning, child: Text(S.of(context).generateAndroidSigning), diff --git a/lib/presentation/screen/project_name_screen/bloc/project_name_screen_bloc.dart b/lib/presentation/screen/project_name_screen/bloc/project_name_screen_bloc.dart index 8b877f3e..44d95201 100644 --- a/lib/presentation/screen/project_name_screen/bloc/project_name_screen_bloc.dart +++ b/lib/presentation/screen/project_name_screen/bloc/project_name_screen_bloc.dart @@ -2,8 +2,8 @@ import 'dart:async'; import 'dart:io'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/domain/usecase/process/get_branches_process_usecase.dart'; import 'package:onix_flutter_bricks/presentation/screen/project_name_screen/bloc/project_name_screen_bloc_imports.dart'; @@ -30,7 +30,7 @@ class ProjectNameScreenBloc extends BaseBloc _isValidProjectName(String projectName) async { + bool _isValidProjectName(String projectName) { final projectExists = - await Directory('${state.config.projectPath}/${projectName.snakeCase}') - .exists(); + Directory('${state.config.projectPath}/${projectName.snakeCase}') + .existsSync(); final isValidName = ProjectNameValidator.isValidName(projectName); return projectName.isNotEmpty && !projectExists && isValidName; } diff --git a/lib/presentation/screen/project_name_screen/project_name_screen.dart b/lib/presentation/screen/project_name_screen/project_name_screen.dart index 9a5a70ca..452d50fd 100644 --- a/lib/presentation/screen/project_name_screen/project_name_screen.dart +++ b/lib/presentation/screen/project_name_screen/project_name_screen.dart @@ -1,12 +1,13 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; +import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_block_state.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/presentation/screen/project_name_screen/bloc/project_name_screen_bloc_imports.dart'; import 'package:onix_flutter_bricks/presentation/screen/project_name_screen/widget/branch_selector_widget.dart'; @@ -31,19 +32,20 @@ class ProjectNameScreen extends StatefulWidget { class _ProjectNameScreenState extends BaseState { - TextEditingController projectNameController = TextEditingController(); - TextEditingController organizationController = TextEditingController(); - FocusNode projectNameFocusNode = FocusNode(); - FocusNode organizationFocusNode = FocusNode(); - FocusNode nextFocusNode = FocusNode(); + final TextEditingController projectNameController = TextEditingController(); + final TextEditingController organizationController = TextEditingController(); + final FocusNode projectNameFocusNode = FocusNode(); + final FocusNode organizationFocusNode = FocusNode(); + final FocusNode nextFocusNode = FocusNode(); + + @override + ProjectNameScreenBloc createBloc() => GetIt.I.get(); @override void onBlocCreated(BuildContext context, ProjectNameScreenBloc bloc) { bloc.add(ProjectNameScreenEvent.init(config: widget.config)); - projectNameController.text = widget.config.projectName; organizationController.text = widget.config.organization; - super.onBlocCreated(context, bloc); } @@ -52,9 +54,7 @@ class _ProjectNameScreenState extends BaseState _buildMainContainer(context, state), - ), + child: blocBuilder(builder: _buildMainContainer), ), ); } @@ -71,15 +71,12 @@ class _ProjectNameScreenState extends BaseState blocOf(context).add( @@ -103,14 +100,11 @@ class _ProjectNameScreenState extends BaseState blocOf(context).add( diff --git a/lib/presentation/screen/project_name_screen/widget/branch_selector_widget.dart b/lib/presentation/screen/project_name_screen/widget/branch_selector_widget.dart index 0c5936fa..e6b07446 100644 --- a/lib/presentation/screen/project_name_screen/widget/branch_selector_widget.dart +++ b/lib/presentation/screen/project_name_screen/widget/branch_selector_widget.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; class BranchSelectorWidget extends StatelessWidget { @@ -20,9 +20,8 @@ class BranchSelectorWidget extends StatelessWidget { return Material( color: context.appColors.darkColor, child: Padding( - padding: const EdgeInsets.all(20.0), + padding: const EdgeInsets.all(20), child: Row( - crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( S.of(context).masonBrickSource, @@ -34,13 +33,15 @@ class BranchSelectorWidget extends StatelessWidget { DropdownButton( value: selectedBranch, icon: const Icon(Icons.keyboard_arrow_down), - items: branches.map((String items) { - return DropdownMenuItem( - value: items, - child: Text(items), - ); - }).toList(), - onChanged: (String? newValue) { + items: branches.map( + (items) { + return DropdownMenuItem( + value: items, + child: Text(items), + ); + }, + ).toList(), + onChanged: (newValue) { if (newValue != null) { onSelected(newValue); } diff --git a/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_bloc.dart b/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_bloc.dart index 0dac7867..9d1c7346 100644 --- a/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_bloc.dart +++ b/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_bloc.dart @@ -1,6 +1,9 @@ import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/core/di/app.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/project_state_manager.dart'; +import 'package:onix_flutter_bricks/domain/repository/screen_repository.dart'; import 'package:onix_flutter_bricks/presentation/screen/project_settings_screen/bloc/project_settings_screen_bloc_imports.dart'; import 'package:onix_flutter_bricks/util/enum/project_localization.dart'; import 'package:onix_flutter_bricks/util/enum/project_router.dart'; @@ -8,21 +11,28 @@ import 'package:onix_flutter_bricks/util/enum/project_theming.dart'; class ProjectSettingsScreenBloc extends BaseBloc { - ProjectSettingsScreenBloc() - : super(const ProjectSettingsScreenStateData(config: Config())) { + final ScreenRepository _screenRepository; + + ProjectSettingsScreenBloc({ + required ScreenRepository screenRepository, + }) : _screenRepository = screenRepository, + super(const ProjectSettingsScreenStateData(config: Config())) { on(_onInit); on(_onFlavorizeChange); on(_onFlavorsChange); on( - _onGenerateSigningKeyChange); + _onGenerateSigningKeyChange, + ); on(_onSigningVarsChange); on(_onUseSonarChange); on(_onGraphQLChange); + on(_onStateManagerChange); on(_onRouterChange); on(_onLocalizationChange); on(_onThemingChange); on(_onFirebaseChange); on(_onScreenUtilChange); + on(_onSentryChange); } void _onInit( @@ -66,8 +76,8 @@ class ProjectSettingsScreenBloc extends BaseBloc emit, + ) { + final isStrategyMatch = screensMatchStrategy(event.stateManager); + + if (!isStrategyMatch) { + logger + ..f('Screens do not match the strategy') + ..f(event.stateManager.strategy.variants); + + final screens = state.config.screens.map((e) { + e.stateVariant = event.stateManager.strategy.variants.first; + return e; + }).toSet(); + + _screenRepository + ..empty() + ..addAll(screens: screens); + + emit( + state.copyWith( + config: state.config.copyWith( + stateManager: event.stateManager, + screens: screens, + ), + ), + ); + + return; + } + + emit( + state.copyWith( + config: state.config.copyWith( + stateManager: event.stateManager, + ), + ), + ); + } + void _onRouterChange( ProjectSettingsScreenEventRouterChange event, Emitter emit, @@ -162,17 +213,43 @@ class ProjectSettingsScreenBloc extends BaseBloc emit, ) { emit( state.copyWith( config: state.config.copyWith( - screenUtil: state.config.platformsList.webOnly - ? false - : !state.config.screenUtil, + screenUtil: + !state.config.platformsList.webOnly && !state.config.screenUtil, ), ), ); } + + void _onSentryChange( + ProjectSettingsScreenEventSentryChange _, + Emitter emit, + ) { + emit( + state.copyWith( + config: state.config.copyWith( + sentry: !state.config.sentry, + ), + ), + ); + } + + bool screensMatchStrategy(ProjectStateManager manager) { + final strategyVariants = manager.strategy.variants; + + var screensMatch = true; + + for (final screen in state.config.screens) { + if (!strategyVariants.contains(screen.stateVariant)) { + screensMatch = false; + } + } + + return screensMatch; + } } diff --git a/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_models.dart b/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_models.dart index 49b8c41d..4febd629 100644 --- a/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_models.dart +++ b/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_models.dart @@ -1,5 +1,6 @@ import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/project_state_manager.dart'; part 'project_settings_screen_models.freezed.dart'; @@ -16,8 +17,9 @@ class ProjectSettingsScreenEvent with _$ProjectSettingsScreenEvent { required String flavors, }) = ProjectSettingsScreenEventFlavorsChange; - const factory ProjectSettingsScreenEvent.generateSigningKeyChange() = - ProjectSettingsScreenEventGenerateSigningKeyChange; + const factory ProjectSettingsScreenEvent.generateSigningKeyChange({ + required bool generateSigningKey, + }) = ProjectSettingsScreenEventGenerateSigningKeyChange; const factory ProjectSettingsScreenEvent.signingVarsChange({ required List signingVars, @@ -29,6 +31,10 @@ class ProjectSettingsScreenEvent with _$ProjectSettingsScreenEvent { const factory ProjectSettingsScreenEvent.graphQLChange() = ProjectSettingsScreenEventGraphQLChange; + const factory ProjectSettingsScreenEvent.stateManagerChange({ + required ProjectStateManager stateManager, + }) = ProjectSettingsScreenEventStateManagerChange; + const factory ProjectSettingsScreenEvent.routerChange() = ProjectSettingsScreenEventRouterChange; @@ -43,6 +49,9 @@ class ProjectSettingsScreenEvent with _$ProjectSettingsScreenEvent { const factory ProjectSettingsScreenEvent.screenUtilChange() = ProjectSettingsScreenEventScreenUtilChange; + + const factory ProjectSettingsScreenEvent.sentryChange() = + ProjectSettingsScreenEventSentryChange; } @freezed diff --git a/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_models.freezed.dart b/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_models.freezed.dart index 84183d43..e1b17c5f 100644 --- a/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_models.freezed.dart +++ b/lib/presentation/screen/project_settings_screen/bloc/project_settings_screen_models.freezed.dart @@ -21,15 +21,18 @@ mixin _$ProjectSettingsScreenEvent { required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) => throw _privateConstructorUsedError; @optionalTypeArgs @@ -37,15 +40,17 @@ mixin _$ProjectSettingsScreenEvent { TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) => throw _privateConstructorUsedError; @optionalTypeArgs @@ -53,15 +58,17 @@ mixin _$ProjectSettingsScreenEvent { TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) => throw _privateConstructorUsedError; @@ -81,6 +88,9 @@ mixin _$ProjectSettingsScreenEvent { useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -92,6 +102,8 @@ mixin _$ProjectSettingsScreenEvent { firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) => throw _privateConstructorUsedError; @optionalTypeArgs @@ -109,6 +121,8 @@ mixin _$ProjectSettingsScreenEvent { useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -119,6 +133,8 @@ mixin _$ProjectSettingsScreenEvent { firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) => throw _privateConstructorUsedError; @optionalTypeArgs @@ -136,6 +152,8 @@ mixin _$ProjectSettingsScreenEvent { useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -146,6 +164,8 @@ mixin _$ProjectSettingsScreenEvent { firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) => throw _privateConstructorUsedError; @@ -254,15 +274,18 @@ class _$ProjectSettingsScreenEventInitImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return init(config); } @@ -273,15 +296,17 @@ class _$ProjectSettingsScreenEventInitImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return init?.call(config); } @@ -292,15 +317,17 @@ class _$ProjectSettingsScreenEventInitImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (init != null) { @@ -326,6 +353,9 @@ class _$ProjectSettingsScreenEventInitImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -337,6 +367,8 @@ class _$ProjectSettingsScreenEventInitImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return init(this); } @@ -357,6 +389,8 @@ class _$ProjectSettingsScreenEventInitImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -367,6 +401,8 @@ class _$ProjectSettingsScreenEventInitImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return init?.call(this); } @@ -387,6 +423,8 @@ class _$ProjectSettingsScreenEventInitImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -397,6 +435,8 @@ class _$ProjectSettingsScreenEventInitImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (init != null) { @@ -464,15 +504,18 @@ class _$ProjectSettingsScreenEventFlavorizeChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return flavorizeChange(); } @@ -483,15 +526,17 @@ class _$ProjectSettingsScreenEventFlavorizeChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return flavorizeChange?.call(); } @@ -502,15 +547,17 @@ class _$ProjectSettingsScreenEventFlavorizeChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (flavorizeChange != null) { @@ -536,6 +583,9 @@ class _$ProjectSettingsScreenEventFlavorizeChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -547,6 +597,8 @@ class _$ProjectSettingsScreenEventFlavorizeChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return flavorizeChange(this); } @@ -567,6 +619,8 @@ class _$ProjectSettingsScreenEventFlavorizeChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -577,6 +631,8 @@ class _$ProjectSettingsScreenEventFlavorizeChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return flavorizeChange?.call(this); } @@ -597,6 +653,8 @@ class _$ProjectSettingsScreenEventFlavorizeChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -607,6 +665,8 @@ class _$ProjectSettingsScreenEventFlavorizeChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (flavorizeChange != null) { @@ -696,15 +756,18 @@ class _$ProjectSettingsScreenEventFlavorsChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return flavorsChange(flavors); } @@ -715,15 +778,17 @@ class _$ProjectSettingsScreenEventFlavorsChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return flavorsChange?.call(flavors); } @@ -734,15 +799,17 @@ class _$ProjectSettingsScreenEventFlavorsChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (flavorsChange != null) { @@ -768,6 +835,9 @@ class _$ProjectSettingsScreenEventFlavorsChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -779,6 +849,8 @@ class _$ProjectSettingsScreenEventFlavorsChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return flavorsChange(this); } @@ -799,6 +871,8 @@ class _$ProjectSettingsScreenEventFlavorsChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -809,6 +883,8 @@ class _$ProjectSettingsScreenEventFlavorsChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return flavorsChange?.call(this); } @@ -829,6 +905,8 @@ class _$ProjectSettingsScreenEventFlavorsChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -839,6 +917,8 @@ class _$ProjectSettingsScreenEventFlavorsChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (flavorsChange != null) { @@ -871,6 +951,8 @@ abstract class _$$ProjectSettingsScreenEventGenerateSigningKeyChangeImplCopyWith then) = __$$ProjectSettingsScreenEventGenerateSigningKeyChangeImplCopyWithImpl< $Res>; + @useResult + $Res call({bool generateSigningKey}); } /// @nodoc @@ -886,28 +968,57 @@ class __$$ProjectSettingsScreenEventGenerateSigningKeyChangeImplCopyWithImpl< $Res Function(_$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl) _then) : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? generateSigningKey = null, + }) { + return _then(_$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl( + generateSigningKey: null == generateSigningKey + ? _value.generateSigningKey + : generateSigningKey // ignore: cast_nullable_to_non_nullable + as bool, + )); + } } /// @nodoc class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl implements ProjectSettingsScreenEventGenerateSigningKeyChange { - const _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl(); + const _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl( + {required this.generateSigningKey}); + + @override + final bool generateSigningKey; @override String toString() { - return 'ProjectSettingsScreenEvent.generateSigningKeyChange()'; + return 'ProjectSettingsScreenEvent.generateSigningKeyChange(generateSigningKey: $generateSigningKey)'; } @override bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl); + other is _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl && + (identical(other.generateSigningKey, generateSigningKey) || + other.generateSigningKey == generateSigningKey)); } @override - int get hashCode => runtimeType.hashCode; + int get hashCode => Object.hash(runtimeType, generateSigningKey); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$ProjectSettingsScreenEventGenerateSigningKeyChangeImplCopyWith< + _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl> + get copyWith => + __$$ProjectSettingsScreenEventGenerateSigningKeyChangeImplCopyWithImpl< + _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl>( + this, _$identity); @override @optionalTypeArgs @@ -915,17 +1026,20 @@ class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { - return generateSigningKeyChange(); + return generateSigningKeyChange(generateSigningKey); } @override @@ -934,17 +1048,19 @@ class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { - return generateSigningKeyChange?.call(); + return generateSigningKeyChange?.call(generateSigningKey); } @override @@ -953,19 +1069,21 @@ class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (generateSigningKeyChange != null) { - return generateSigningKeyChange(); + return generateSigningKeyChange(generateSigningKey); } return orElse(); } @@ -987,6 +1105,9 @@ class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -998,6 +1119,8 @@ class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return generateSigningKeyChange(this); } @@ -1018,6 +1141,8 @@ class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -1028,6 +1153,8 @@ class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return generateSigningKeyChange?.call(this); } @@ -1048,6 +1175,8 @@ class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -1058,6 +1187,8 @@ class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (generateSigningKeyChange != null) { @@ -1069,8 +1200,15 @@ class _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl abstract class ProjectSettingsScreenEventGenerateSigningKeyChange implements ProjectSettingsScreenEvent { - const factory ProjectSettingsScreenEventGenerateSigningKeyChange() = + const factory ProjectSettingsScreenEventGenerateSigningKeyChange( + {required final bool generateSigningKey}) = _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl; + + bool get generateSigningKey; + @JsonKey(ignore: true) + _$$ProjectSettingsScreenEventGenerateSigningKeyChangeImplCopyWith< + _$ProjectSettingsScreenEventGenerateSigningKeyChangeImpl> + get copyWith => throw _privateConstructorUsedError; } /// @nodoc @@ -1160,15 +1298,18 @@ class _$ProjectSettingsScreenEventSigningVarsChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return signingVarsChange(signingVars); } @@ -1179,15 +1320,17 @@ class _$ProjectSettingsScreenEventSigningVarsChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return signingVarsChange?.call(signingVars); } @@ -1198,15 +1341,17 @@ class _$ProjectSettingsScreenEventSigningVarsChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (signingVarsChange != null) { @@ -1232,6 +1377,9 @@ class _$ProjectSettingsScreenEventSigningVarsChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -1243,6 +1391,8 @@ class _$ProjectSettingsScreenEventSigningVarsChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return signingVarsChange(this); } @@ -1263,6 +1413,8 @@ class _$ProjectSettingsScreenEventSigningVarsChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -1273,6 +1425,8 @@ class _$ProjectSettingsScreenEventSigningVarsChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return signingVarsChange?.call(this); } @@ -1293,6 +1447,8 @@ class _$ProjectSettingsScreenEventSigningVarsChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -1303,6 +1459,8 @@ class _$ProjectSettingsScreenEventSigningVarsChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (signingVarsChange != null) { @@ -1371,15 +1529,18 @@ class _$ProjectSettingsScreenEventUseSonarChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return useSonarChange(); } @@ -1390,15 +1551,17 @@ class _$ProjectSettingsScreenEventUseSonarChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return useSonarChange?.call(); } @@ -1409,15 +1572,17 @@ class _$ProjectSettingsScreenEventUseSonarChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (useSonarChange != null) { @@ -1443,6 +1608,9 @@ class _$ProjectSettingsScreenEventUseSonarChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -1454,6 +1622,8 @@ class _$ProjectSettingsScreenEventUseSonarChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return useSonarChange(this); } @@ -1474,6 +1644,8 @@ class _$ProjectSettingsScreenEventUseSonarChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -1484,6 +1656,8 @@ class _$ProjectSettingsScreenEventUseSonarChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return useSonarChange?.call(this); } @@ -1504,6 +1678,8 @@ class _$ProjectSettingsScreenEventUseSonarChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -1514,6 +1690,8 @@ class _$ProjectSettingsScreenEventUseSonarChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (useSonarChange != null) { @@ -1575,15 +1753,18 @@ class _$ProjectSettingsScreenEventGraphQLChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return graphQLChange(); } @@ -1594,15 +1775,17 @@ class _$ProjectSettingsScreenEventGraphQLChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return graphQLChange?.call(); } @@ -1613,15 +1796,17 @@ class _$ProjectSettingsScreenEventGraphQLChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (graphQLChange != null) { @@ -1647,6 +1832,9 @@ class _$ProjectSettingsScreenEventGraphQLChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -1658,6 +1846,8 @@ class _$ProjectSettingsScreenEventGraphQLChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return graphQLChange(this); } @@ -1678,6 +1868,8 @@ class _$ProjectSettingsScreenEventGraphQLChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -1688,6 +1880,8 @@ class _$ProjectSettingsScreenEventGraphQLChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return graphQLChange?.call(this); } @@ -1708,6 +1902,8 @@ class _$ProjectSettingsScreenEventGraphQLChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -1718,6 +1914,8 @@ class _$ProjectSettingsScreenEventGraphQLChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (graphQLChange != null) { @@ -1733,6 +1931,271 @@ abstract class ProjectSettingsScreenEventGraphQLChange _$ProjectSettingsScreenEventGraphQLChangeImpl; } +/// @nodoc +abstract class _$$ProjectSettingsScreenEventStateManagerChangeImplCopyWith< + $Res> { + factory _$$ProjectSettingsScreenEventStateManagerChangeImplCopyWith( + _$ProjectSettingsScreenEventStateManagerChangeImpl value, + $Res Function(_$ProjectSettingsScreenEventStateManagerChangeImpl) + then) = + __$$ProjectSettingsScreenEventStateManagerChangeImplCopyWithImpl<$Res>; + @useResult + $Res call({ProjectStateManager stateManager}); +} + +/// @nodoc +class __$$ProjectSettingsScreenEventStateManagerChangeImplCopyWithImpl<$Res> + extends _$ProjectSettingsScreenEventCopyWithImpl<$Res, + _$ProjectSettingsScreenEventStateManagerChangeImpl> + implements + _$$ProjectSettingsScreenEventStateManagerChangeImplCopyWith<$Res> { + __$$ProjectSettingsScreenEventStateManagerChangeImplCopyWithImpl( + _$ProjectSettingsScreenEventStateManagerChangeImpl _value, + $Res Function(_$ProjectSettingsScreenEventStateManagerChangeImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? stateManager = null, + }) { + return _then(_$ProjectSettingsScreenEventStateManagerChangeImpl( + stateManager: null == stateManager + ? _value.stateManager + : stateManager // ignore: cast_nullable_to_non_nullable + as ProjectStateManager, + )); + } +} + +/// @nodoc + +class _$ProjectSettingsScreenEventStateManagerChangeImpl + implements ProjectSettingsScreenEventStateManagerChange { + const _$ProjectSettingsScreenEventStateManagerChangeImpl( + {required this.stateManager}); + + @override + final ProjectStateManager stateManager; + + @override + String toString() { + return 'ProjectSettingsScreenEvent.stateManagerChange(stateManager: $stateManager)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ProjectSettingsScreenEventStateManagerChangeImpl && + (identical(other.stateManager, stateManager) || + other.stateManager == stateManager)); + } + + @override + int get hashCode => Object.hash(runtimeType, stateManager); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$ProjectSettingsScreenEventStateManagerChangeImplCopyWith< + _$ProjectSettingsScreenEventStateManagerChangeImpl> + get copyWith => + __$$ProjectSettingsScreenEventStateManagerChangeImplCopyWithImpl< + _$ProjectSettingsScreenEventStateManagerChangeImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function(Config config) init, + required TResult Function() flavorizeChange, + required TResult Function(String flavors) flavorsChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, + required TResult Function(List signingVars) signingVarsChange, + required TResult Function() useSonarChange, + required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, + required TResult Function() routerChange, + required TResult Function() localizationChange, + required TResult Function() themingChange, + required TResult Function() firebaseChange, + required TResult Function() screenUtilChange, + required TResult Function() sentryChange, + }) { + return stateManagerChange(stateManager); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(Config config)? init, + TResult? Function()? flavorizeChange, + TResult? Function(String flavors)? flavorsChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, + TResult? Function(List signingVars)? signingVarsChange, + TResult? Function()? useSonarChange, + TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, + TResult? Function()? routerChange, + TResult? Function()? localizationChange, + TResult? Function()? themingChange, + TResult? Function()? firebaseChange, + TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, + }) { + return stateManagerChange?.call(stateManager); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(Config config)? init, + TResult Function()? flavorizeChange, + TResult Function(String flavors)? flavorsChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, + TResult Function(List signingVars)? signingVarsChange, + TResult Function()? useSonarChange, + TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, + TResult Function()? routerChange, + TResult Function()? localizationChange, + TResult Function()? themingChange, + TResult Function()? firebaseChange, + TResult Function()? screenUtilChange, + TResult Function()? sentryChange, + required TResult orElse(), + }) { + if (stateManagerChange != null) { + return stateManagerChange(stateManager); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(ProjectSettingsScreenEventInit value) init, + required TResult Function(ProjectSettingsScreenEventFlavorizeChange value) + flavorizeChange, + required TResult Function(ProjectSettingsScreenEventFlavorsChange value) + flavorsChange, + required TResult Function( + ProjectSettingsScreenEventGenerateSigningKeyChange value) + generateSigningKeyChange, + required TResult Function(ProjectSettingsScreenEventSigningVarsChange value) + signingVarsChange, + required TResult Function(ProjectSettingsScreenEventUseSonarChange value) + useSonarChange, + required TResult Function(ProjectSettingsScreenEventGraphQLChange value) + graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, + required TResult Function(ProjectSettingsScreenEventRouterChange value) + routerChange, + required TResult Function( + ProjectSettingsScreenEventLocalizationChange value) + localizationChange, + required TResult Function(ProjectSettingsScreenEventThemingChange value) + themingChange, + required TResult Function(ProjectSettingsScreenEventFirebaseChange value) + firebaseChange, + required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) + screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, + }) { + return stateManagerChange(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(ProjectSettingsScreenEventInit value)? init, + TResult? Function(ProjectSettingsScreenEventFlavorizeChange value)? + flavorizeChange, + TResult? Function(ProjectSettingsScreenEventFlavorsChange value)? + flavorsChange, + TResult? Function(ProjectSettingsScreenEventGenerateSigningKeyChange value)? + generateSigningKeyChange, + TResult? Function(ProjectSettingsScreenEventSigningVarsChange value)? + signingVarsChange, + TResult? Function(ProjectSettingsScreenEventUseSonarChange value)? + useSonarChange, + TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? + graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, + TResult? Function(ProjectSettingsScreenEventRouterChange value)? + routerChange, + TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? + localizationChange, + TResult? Function(ProjectSettingsScreenEventThemingChange value)? + themingChange, + TResult? Function(ProjectSettingsScreenEventFirebaseChange value)? + firebaseChange, + TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? + screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, + }) { + return stateManagerChange?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(ProjectSettingsScreenEventInit value)? init, + TResult Function(ProjectSettingsScreenEventFlavorizeChange value)? + flavorizeChange, + TResult Function(ProjectSettingsScreenEventFlavorsChange value)? + flavorsChange, + TResult Function(ProjectSettingsScreenEventGenerateSigningKeyChange value)? + generateSigningKeyChange, + TResult Function(ProjectSettingsScreenEventSigningVarsChange value)? + signingVarsChange, + TResult Function(ProjectSettingsScreenEventUseSonarChange value)? + useSonarChange, + TResult Function(ProjectSettingsScreenEventGraphQLChange value)? + graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, + TResult Function(ProjectSettingsScreenEventRouterChange value)? + routerChange, + TResult Function(ProjectSettingsScreenEventLocalizationChange value)? + localizationChange, + TResult Function(ProjectSettingsScreenEventThemingChange value)? + themingChange, + TResult Function(ProjectSettingsScreenEventFirebaseChange value)? + firebaseChange, + TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? + screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, + required TResult orElse(), + }) { + if (stateManagerChange != null) { + return stateManagerChange(this); + } + return orElse(); + } +} + +abstract class ProjectSettingsScreenEventStateManagerChange + implements ProjectSettingsScreenEvent { + const factory ProjectSettingsScreenEventStateManagerChange( + {required final ProjectStateManager stateManager}) = + _$ProjectSettingsScreenEventStateManagerChangeImpl; + + ProjectStateManager get stateManager; + @JsonKey(ignore: true) + _$$ProjectSettingsScreenEventStateManagerChangeImplCopyWith< + _$ProjectSettingsScreenEventStateManagerChangeImpl> + get copyWith => throw _privateConstructorUsedError; +} + /// @nodoc abstract class _$$ProjectSettingsScreenEventRouterChangeImplCopyWith<$Res> { factory _$$ProjectSettingsScreenEventRouterChangeImplCopyWith( @@ -1779,15 +2242,18 @@ class _$ProjectSettingsScreenEventRouterChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return routerChange(); } @@ -1798,15 +2264,17 @@ class _$ProjectSettingsScreenEventRouterChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return routerChange?.call(); } @@ -1817,15 +2285,17 @@ class _$ProjectSettingsScreenEventRouterChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (routerChange != null) { @@ -1851,6 +2321,9 @@ class _$ProjectSettingsScreenEventRouterChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -1862,6 +2335,8 @@ class _$ProjectSettingsScreenEventRouterChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return routerChange(this); } @@ -1882,6 +2357,8 @@ class _$ProjectSettingsScreenEventRouterChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -1892,6 +2369,8 @@ class _$ProjectSettingsScreenEventRouterChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return routerChange?.call(this); } @@ -1912,6 +2391,8 @@ class _$ProjectSettingsScreenEventRouterChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -1922,6 +2403,8 @@ class _$ProjectSettingsScreenEventRouterChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (routerChange != null) { @@ -1986,15 +2469,18 @@ class _$ProjectSettingsScreenEventLocalizationChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return localizationChange(); } @@ -2005,15 +2491,17 @@ class _$ProjectSettingsScreenEventLocalizationChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return localizationChange?.call(); } @@ -2024,15 +2512,17 @@ class _$ProjectSettingsScreenEventLocalizationChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (localizationChange != null) { @@ -2058,6 +2548,9 @@ class _$ProjectSettingsScreenEventLocalizationChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -2069,6 +2562,8 @@ class _$ProjectSettingsScreenEventLocalizationChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return localizationChange(this); } @@ -2089,6 +2584,8 @@ class _$ProjectSettingsScreenEventLocalizationChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -2099,6 +2596,8 @@ class _$ProjectSettingsScreenEventLocalizationChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return localizationChange?.call(this); } @@ -2119,6 +2618,8 @@ class _$ProjectSettingsScreenEventLocalizationChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -2129,6 +2630,8 @@ class _$ProjectSettingsScreenEventLocalizationChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (localizationChange != null) { @@ -2190,15 +2693,18 @@ class _$ProjectSettingsScreenEventThemingChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return themingChange(); } @@ -2209,15 +2715,17 @@ class _$ProjectSettingsScreenEventThemingChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return themingChange?.call(); } @@ -2228,15 +2736,17 @@ class _$ProjectSettingsScreenEventThemingChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (themingChange != null) { @@ -2262,6 +2772,9 @@ class _$ProjectSettingsScreenEventThemingChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -2273,6 +2786,8 @@ class _$ProjectSettingsScreenEventThemingChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return themingChange(this); } @@ -2293,6 +2808,8 @@ class _$ProjectSettingsScreenEventThemingChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -2303,6 +2820,8 @@ class _$ProjectSettingsScreenEventThemingChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return themingChange?.call(this); } @@ -2323,6 +2842,8 @@ class _$ProjectSettingsScreenEventThemingChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -2333,6 +2854,8 @@ class _$ProjectSettingsScreenEventThemingChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (themingChange != null) { @@ -2394,15 +2917,18 @@ class _$ProjectSettingsScreenEventFirebaseChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return firebaseChange(); } @@ -2413,15 +2939,17 @@ class _$ProjectSettingsScreenEventFirebaseChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return firebaseChange?.call(); } @@ -2432,15 +2960,17 @@ class _$ProjectSettingsScreenEventFirebaseChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (firebaseChange != null) { @@ -2466,6 +2996,9 @@ class _$ProjectSettingsScreenEventFirebaseChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -2477,6 +3010,8 @@ class _$ProjectSettingsScreenEventFirebaseChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return firebaseChange(this); } @@ -2497,6 +3032,8 @@ class _$ProjectSettingsScreenEventFirebaseChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -2507,6 +3044,8 @@ class _$ProjectSettingsScreenEventFirebaseChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return firebaseChange?.call(this); } @@ -2527,6 +3066,8 @@ class _$ProjectSettingsScreenEventFirebaseChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -2537,6 +3078,8 @@ class _$ProjectSettingsScreenEventFirebaseChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (firebaseChange != null) { @@ -2599,15 +3142,18 @@ class _$ProjectSettingsScreenEventScreenUtilChangeImpl required TResult Function(Config config) init, required TResult Function() flavorizeChange, required TResult Function(String flavors) flavorsChange, - required TResult Function() generateSigningKeyChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, required TResult Function(List signingVars) signingVarsChange, required TResult Function() useSonarChange, required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, required TResult Function() routerChange, required TResult Function() localizationChange, required TResult Function() themingChange, required TResult Function() firebaseChange, required TResult Function() screenUtilChange, + required TResult Function() sentryChange, }) { return screenUtilChange(); } @@ -2618,15 +3164,17 @@ class _$ProjectSettingsScreenEventScreenUtilChangeImpl TResult? Function(Config config)? init, TResult? Function()? flavorizeChange, TResult? Function(String flavors)? flavorsChange, - TResult? Function()? generateSigningKeyChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, TResult? Function(List signingVars)? signingVarsChange, TResult? Function()? useSonarChange, TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, TResult? Function()? routerChange, TResult? Function()? localizationChange, TResult? Function()? themingChange, TResult? Function()? firebaseChange, TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, }) { return screenUtilChange?.call(); } @@ -2637,15 +3185,17 @@ class _$ProjectSettingsScreenEventScreenUtilChangeImpl TResult Function(Config config)? init, TResult Function()? flavorizeChange, TResult Function(String flavors)? flavorsChange, - TResult Function()? generateSigningKeyChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, TResult Function(List signingVars)? signingVarsChange, TResult Function()? useSonarChange, TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, TResult Function()? routerChange, TResult Function()? localizationChange, TResult Function()? themingChange, TResult Function()? firebaseChange, TResult Function()? screenUtilChange, + TResult Function()? sentryChange, required TResult orElse(), }) { if (screenUtilChange != null) { @@ -2671,6 +3221,9 @@ class _$ProjectSettingsScreenEventScreenUtilChangeImpl useSonarChange, required TResult Function(ProjectSettingsScreenEventGraphQLChange value) graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, required TResult Function(ProjectSettingsScreenEventRouterChange value) routerChange, required TResult Function( @@ -2682,6 +3235,8 @@ class _$ProjectSettingsScreenEventScreenUtilChangeImpl firebaseChange, required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, }) { return screenUtilChange(this); } @@ -2702,6 +3257,8 @@ class _$ProjectSettingsScreenEventScreenUtilChangeImpl useSonarChange, TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult? Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -2712,6 +3269,8 @@ class _$ProjectSettingsScreenEventScreenUtilChangeImpl firebaseChange, TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, }) { return screenUtilChange?.call(this); } @@ -2732,6 +3291,8 @@ class _$ProjectSettingsScreenEventScreenUtilChangeImpl useSonarChange, TResult Function(ProjectSettingsScreenEventGraphQLChange value)? graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, TResult Function(ProjectSettingsScreenEventRouterChange value)? routerChange, TResult Function(ProjectSettingsScreenEventLocalizationChange value)? @@ -2742,6 +3303,8 @@ class _$ProjectSettingsScreenEventScreenUtilChangeImpl firebaseChange, TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, required TResult orElse(), }) { if (screenUtilChange != null) { @@ -2757,6 +3320,230 @@ abstract class ProjectSettingsScreenEventScreenUtilChange _$ProjectSettingsScreenEventScreenUtilChangeImpl; } +/// @nodoc +abstract class _$$ProjectSettingsScreenEventSentryChangeImplCopyWith<$Res> { + factory _$$ProjectSettingsScreenEventSentryChangeImplCopyWith( + _$ProjectSettingsScreenEventSentryChangeImpl value, + $Res Function(_$ProjectSettingsScreenEventSentryChangeImpl) then) = + __$$ProjectSettingsScreenEventSentryChangeImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$ProjectSettingsScreenEventSentryChangeImplCopyWithImpl<$Res> + extends _$ProjectSettingsScreenEventCopyWithImpl<$Res, + _$ProjectSettingsScreenEventSentryChangeImpl> + implements _$$ProjectSettingsScreenEventSentryChangeImplCopyWith<$Res> { + __$$ProjectSettingsScreenEventSentryChangeImplCopyWithImpl( + _$ProjectSettingsScreenEventSentryChangeImpl _value, + $Res Function(_$ProjectSettingsScreenEventSentryChangeImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$ProjectSettingsScreenEventSentryChangeImpl + implements ProjectSettingsScreenEventSentryChange { + const _$ProjectSettingsScreenEventSentryChangeImpl(); + + @override + String toString() { + return 'ProjectSettingsScreenEvent.sentryChange()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ProjectSettingsScreenEventSentryChangeImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function(Config config) init, + required TResult Function() flavorizeChange, + required TResult Function(String flavors) flavorsChange, + required TResult Function(bool generateSigningKey) generateSigningKeyChange, + required TResult Function(List signingVars) signingVarsChange, + required TResult Function() useSonarChange, + required TResult Function() graphQLChange, + required TResult Function(ProjectStateManager stateManager) + stateManagerChange, + required TResult Function() routerChange, + required TResult Function() localizationChange, + required TResult Function() themingChange, + required TResult Function() firebaseChange, + required TResult Function() screenUtilChange, + required TResult Function() sentryChange, + }) { + return sentryChange(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(Config config)? init, + TResult? Function()? flavorizeChange, + TResult? Function(String flavors)? flavorsChange, + TResult? Function(bool generateSigningKey)? generateSigningKeyChange, + TResult? Function(List signingVars)? signingVarsChange, + TResult? Function()? useSonarChange, + TResult? Function()? graphQLChange, + TResult? Function(ProjectStateManager stateManager)? stateManagerChange, + TResult? Function()? routerChange, + TResult? Function()? localizationChange, + TResult? Function()? themingChange, + TResult? Function()? firebaseChange, + TResult? Function()? screenUtilChange, + TResult? Function()? sentryChange, + }) { + return sentryChange?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(Config config)? init, + TResult Function()? flavorizeChange, + TResult Function(String flavors)? flavorsChange, + TResult Function(bool generateSigningKey)? generateSigningKeyChange, + TResult Function(List signingVars)? signingVarsChange, + TResult Function()? useSonarChange, + TResult Function()? graphQLChange, + TResult Function(ProjectStateManager stateManager)? stateManagerChange, + TResult Function()? routerChange, + TResult Function()? localizationChange, + TResult Function()? themingChange, + TResult Function()? firebaseChange, + TResult Function()? screenUtilChange, + TResult Function()? sentryChange, + required TResult orElse(), + }) { + if (sentryChange != null) { + return sentryChange(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(ProjectSettingsScreenEventInit value) init, + required TResult Function(ProjectSettingsScreenEventFlavorizeChange value) + flavorizeChange, + required TResult Function(ProjectSettingsScreenEventFlavorsChange value) + flavorsChange, + required TResult Function( + ProjectSettingsScreenEventGenerateSigningKeyChange value) + generateSigningKeyChange, + required TResult Function(ProjectSettingsScreenEventSigningVarsChange value) + signingVarsChange, + required TResult Function(ProjectSettingsScreenEventUseSonarChange value) + useSonarChange, + required TResult Function(ProjectSettingsScreenEventGraphQLChange value) + graphQLChange, + required TResult Function( + ProjectSettingsScreenEventStateManagerChange value) + stateManagerChange, + required TResult Function(ProjectSettingsScreenEventRouterChange value) + routerChange, + required TResult Function( + ProjectSettingsScreenEventLocalizationChange value) + localizationChange, + required TResult Function(ProjectSettingsScreenEventThemingChange value) + themingChange, + required TResult Function(ProjectSettingsScreenEventFirebaseChange value) + firebaseChange, + required TResult Function(ProjectSettingsScreenEventScreenUtilChange value) + screenUtilChange, + required TResult Function(ProjectSettingsScreenEventSentryChange value) + sentryChange, + }) { + return sentryChange(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(ProjectSettingsScreenEventInit value)? init, + TResult? Function(ProjectSettingsScreenEventFlavorizeChange value)? + flavorizeChange, + TResult? Function(ProjectSettingsScreenEventFlavorsChange value)? + flavorsChange, + TResult? Function(ProjectSettingsScreenEventGenerateSigningKeyChange value)? + generateSigningKeyChange, + TResult? Function(ProjectSettingsScreenEventSigningVarsChange value)? + signingVarsChange, + TResult? Function(ProjectSettingsScreenEventUseSonarChange value)? + useSonarChange, + TResult? Function(ProjectSettingsScreenEventGraphQLChange value)? + graphQLChange, + TResult? Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, + TResult? Function(ProjectSettingsScreenEventRouterChange value)? + routerChange, + TResult? Function(ProjectSettingsScreenEventLocalizationChange value)? + localizationChange, + TResult? Function(ProjectSettingsScreenEventThemingChange value)? + themingChange, + TResult? Function(ProjectSettingsScreenEventFirebaseChange value)? + firebaseChange, + TResult? Function(ProjectSettingsScreenEventScreenUtilChange value)? + screenUtilChange, + TResult? Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, + }) { + return sentryChange?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(ProjectSettingsScreenEventInit value)? init, + TResult Function(ProjectSettingsScreenEventFlavorizeChange value)? + flavorizeChange, + TResult Function(ProjectSettingsScreenEventFlavorsChange value)? + flavorsChange, + TResult Function(ProjectSettingsScreenEventGenerateSigningKeyChange value)? + generateSigningKeyChange, + TResult Function(ProjectSettingsScreenEventSigningVarsChange value)? + signingVarsChange, + TResult Function(ProjectSettingsScreenEventUseSonarChange value)? + useSonarChange, + TResult Function(ProjectSettingsScreenEventGraphQLChange value)? + graphQLChange, + TResult Function(ProjectSettingsScreenEventStateManagerChange value)? + stateManagerChange, + TResult Function(ProjectSettingsScreenEventRouterChange value)? + routerChange, + TResult Function(ProjectSettingsScreenEventLocalizationChange value)? + localizationChange, + TResult Function(ProjectSettingsScreenEventThemingChange value)? + themingChange, + TResult Function(ProjectSettingsScreenEventFirebaseChange value)? + firebaseChange, + TResult Function(ProjectSettingsScreenEventScreenUtilChange value)? + screenUtilChange, + TResult Function(ProjectSettingsScreenEventSentryChange value)? + sentryChange, + required TResult orElse(), + }) { + if (sentryChange != null) { + return sentryChange(this); + } + return orElse(); + } +} + +abstract class ProjectSettingsScreenEventSentryChange + implements ProjectSettingsScreenEvent { + const factory ProjectSettingsScreenEventSentryChange() = + _$ProjectSettingsScreenEventSentryChangeImpl; +} + /// @nodoc mixin _$ProjectSettingsScreenSR { @optionalTypeArgs diff --git a/lib/presentation/screen/project_settings_screen/project_settings_screen.dart b/lib/presentation/screen/project_settings_screen/project_settings_screen.dart index c0cb1fd4..e6d3801d 100644 --- a/lib/presentation/screen/project_settings_screen/project_settings_screen.dart +++ b/lib/presentation/screen/project_settings_screen/project_settings_screen.dart @@ -1,24 +1,17 @@ import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; +import 'package:gap/gap.dart'; +import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_block_state.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/presentation/screen/project_settings_screen/bloc/project_settings_screen_bloc_imports.dart'; -import 'package:onix_flutter_bricks/presentation/screen/project_settings_screen/widgets/signing_dialog.dart'; -import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; +import 'package:onix_flutter_bricks/presentation/screen/project_settings_screen/widgets/left_part.dart'; +import 'package:onix_flutter_bricks/presentation/screen/project_settings_screen/widgets/right_part.dart'; import 'package:onix_flutter_bricks/presentation/widget/buttons/navigation_button_bar.dart'; -import 'package:onix_flutter_bricks/presentation/widget/inputs/labeled_segmented_control.dart'; -import 'package:onix_flutter_bricks/presentation/widget/inputs/switch_with_label.dart'; -import 'package:onix_flutter_bricks/presentation/widget/inputs/text_field_with_label.dart'; import 'package:onix_flutter_bricks/presentation/widget/title_bar.dart'; -import 'package:onix_flutter_bricks/util/enum/project_localization.dart'; -import 'package:onix_flutter_bricks/util/enum/project_router.dart'; -import 'package:onix_flutter_bricks/util/enum/project_theming.dart'; -import 'package:onix_flutter_bricks/util/extra_space_formatter.dart'; class ProjectSettingsScreen extends StatefulWidget { final Config config; @@ -35,8 +28,11 @@ class ProjectSettingsScreen extends StatefulWidget { class _ProjectSettingsScreenState extends BaseState { final TextEditingController _flavorsController = TextEditingController(); + //final double _height = 350; - final double _height = 350; + @override + ProjectSettingsScreenBloc createBloc() => + GetIt.I.get(); @override Widget buildWidget(BuildContext context) { @@ -47,8 +43,8 @@ class _ProjectSettingsScreenState extends BaseState _buildMainContainer(context, state), + child: blocBuilder( + builder: _buildMainContainer, ), ), ), @@ -64,7 +60,9 @@ class _ProjectSettingsScreenState extends BaseState blocOf(context).add( - const ProjectSettingsScreenEventFlavorizeChange()), - ), - const Delimiter.height(20), - ], - if (!state.config.platformsList.webOnly && - state.config.flavorize) ...[ - TextFieldWithLabel( - label: S.of(context).addFlavors, - expanded: true, - subLabel: S.of(context).spaceSeparated, - textController: _flavorsController, - inputFormatters: [ - FilteringTextInputFormatter.allow( - RegExp(r'[a-zA-Z\s]', unicode: true), - ), - ExtraSpaceFormatter(), - ], - onChanged: () => blocOf(context) - .add(ProjectSettingsScreenEventFlavorsChange( - flavors: _flavorsController.text, - )), - ), - const Delimiter.height(20), - ], - if (state.config.platformsList.mobile) ...[ - SwitchWithLabel( - label: S.of(context).generateSigningKey, - initialValue: state.config.generateSigningKey, - subLabel: - S.of(context).dialogWillOpenInSeparateWindow, - valueSetter: (value) { - blocOf(context).add( - const ProjectSettingsScreenEventGenerateSigningKeyChange()); - if (value) { - _showSigningVarsDialog( - context: context, - state: state, - ); - } - }, - ), - TextButton( - onPressed: () => _showSigningVarsDialog( - context: context, state: state), - style: TextButton.styleFrom( - padding: EdgeInsets.zero, - ), - child: Text(S.of(context).modifySigningVars), - ), - const Delimiter.height(20), - ], - SwitchWithLabel( - label: S.of(context).useSonar, - initialValue: state.config.useSonar, - valueSetter: (_) => blocOf(context).add( - const ProjectSettingsScreenEventUseSonarChange()), - ), - const Delimiter.height(20), - SwitchWithLabel( - label: S.of(context).integrateGraphQl, - initialValue: state.config.graphql, - valueSetter: (_) => blocOf(context).add( - const ProjectSettingsScreenEventGraphQLChange()), - ), - ], - ), + child: LeftPart( + bloc: blocOf(context), + flavorsController: _flavorsController, + //height: _height, ), ), const Delimiter.width(20), Expanded( - child: Container( - height: _height, - padding: const EdgeInsets.all(20), - decoration: BoxDecoration( - border: - Border.all(color: context.appColors.contrastColor), - borderRadius: BorderRadius.circular(10), - ), - child: Column( - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.end, - mainAxisSize: MainAxisSize.min, - children: [ - LabeledSegmentedControl( - label: S.of(context).router, - values: - ProjectRouter.values.map((e) => e.name).toList(), - onChange: (_) => blocOf(context).add( - const ProjectSettingsScreenEventRouterChange()), - selectedValue: state.config.router.name, - ), - const Delimiter.height(20), - LabeledSegmentedControl( - label: S.of(context).localization, - values: ProjectLocalization.values - .map((e) => e.name) - .toList(), - onChange: (_) => blocOf(context).add( - const ProjectSettingsScreenEventLocalizationChange()), - selectedValue: state.config.localization.name, - ), - const Delimiter.height(20), - LabeledSegmentedControl( - label: S.of(context).theming, - values: - ProjectTheming.values.map((e) => e.name).toList(), - onChange: (_) => blocOf(context).add( - const ProjectSettingsScreenEventThemingChange()), - selectedValue: state.config.theming.name, - ), - const Delimiter.height(20), - SwitchWithLabel( - label: S.of(context).firebaseAuth, - initialValue: state.config.firebaseAuth, - valueSetter: (_) => blocOf(context).add( - const ProjectSettingsScreenEventFirebaseChange()), - ), - if (!state.config.platformsList.webOnly) ...[ - const Delimiter.height(20), - SwitchWithLabel( - label: S.of(context).useScreenUtil, - initialValue: state.config.screenUtil, - valueSetter: (_) => blocOf(context).add( - const ProjectSettingsScreenEvent - .screenUtilChange(), - ), - ), - ], - ], - ), + child: RightPart( + bloc: blocOf(context), + //height: _height, ), ), ], @@ -254,27 +114,6 @@ class _ProjectSettingsScreenState extends BaseState>( - context: context, - barrierDismissible: false, - builder: (ctx) => SigningDialog( - signingVars: state.config.signingVars, - ), - ).then( - (signingVars) { - blocOf(context).add( - ProjectSettingsScreenEventSigningVarsChange( - signingVars: - signingVars ?? blocOf(context).state.config.signingVars), - ); - }, - ); - } - void _goBack(ProjectSettingsScreenState state) => context.go( AppRouter.platformsScreen, extra: state.config, diff --git a/lib/presentation/screen/project_settings_screen/widgets/left_part.dart b/lib/presentation/screen/project_settings_screen/widgets/left_part.dart new file mode 100644 index 00000000..db051f4b --- /dev/null +++ b/lib/presentation/screen/project_settings_screen/widgets/left_part.dart @@ -0,0 +1,156 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:gap/gap.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/presentation/screen/project_settings_screen/bloc/project_settings_screen_bloc_imports.dart'; +import 'package:onix_flutter_bricks/presentation/screen/project_settings_screen/widgets/signing_dialog.dart'; +import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; +import 'package:onix_flutter_bricks/presentation/widget/inputs/switch_with_label.dart'; +import 'package:onix_flutter_bricks/presentation/widget/inputs/text_field_with_label.dart'; +import 'package:onix_flutter_bricks/util/extra_space_formatter.dart'; + +class LeftPart extends StatelessWidget { + final ProjectSettingsScreenBloc bloc; + final TextEditingController flavorsController; + + const LeftPart({ + required this.bloc, + required this.flavorsController, + super.key, + }); + + @override + Widget build(BuildContext context) { + final state = bloc.state; + + return Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + border: Border.all( + color: context.appColors.contrastColor, + ), + borderRadius: BorderRadius.circular(10), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!state.config.platformsList.webOnly) ...[ + SwitchWithLabel( + label: S.of(context).flavorize, + initialValue: state.config.flavorize, + subLabel: S.of(context).willBeAddedAutomatically, + valueSetter: (_) => bloc.add( + const ProjectSettingsScreenEventFlavorizeChange(), + ), + ), + const Gap(20), + ], + if (!state.config.platformsList.webOnly && + state.config.flavorize) ...[ + TextFieldWithLabel( + label: S.of(context).addFlavors, + expanded: true, + subLabel: S.of(context).spaceSeparated, + textController: flavorsController, + inputFormatters: [ + FilteringTextInputFormatter.allow( + RegExp(r'[a-zA-Z\s]', unicode: true), + ), + ExtraSpaceFormatter(), + ], + onChanged: () => bloc.add( + ProjectSettingsScreenEventFlavorsChange( + flavors: flavorsController.text, + ), + ), + ), + const Gap(20), + ], + if (state.config.platformsList.mobile) ...[ + SwitchWithLabel( + label: S.of(context).generateSigningKey, + initialValue: state.config.generateSigningKey, + subLabel: S.of(context).dialogWillOpenInSeparateWindow, + valueSetter: (value) { + bloc.add( + ProjectSettingsScreenEventGenerateSigningKeyChange( + generateSigningKey: value, + ), + ); + if (value) { + _showSigningVarsDialog( + context: context, + state: state, + toggleGenerateSigningKey: true, + ); + } + }, + ), + TextButton( + onPressed: () => + _showSigningVarsDialog(context: context, state: state), + style: TextButton.styleFrom( + padding: EdgeInsets.zero, + ), + child: Text(S.of(context).modifySigningVars), + ), + const Gap(20), + ], + SwitchWithLabel( + label: S.of(context).useSonar, + initialValue: state.config.useSonar, + valueSetter: (_) => + bloc.add(const ProjectSettingsScreenEventUseSonarChange()), + ), + const Gap(20), + SwitchWithLabel( + label: S.of(context).integrateGraphQl, + initialValue: state.config.graphql, + valueSetter: (_) => + bloc.add(const ProjectSettingsScreenEventGraphQLChange()), + ), + const Gap(20), + SwitchWithLabel( + label: S.of(context).integrateSentry, + initialValue: state.config.sentry, + valueSetter: (_) => bloc.add( + const ProjectSettingsScreenEvent.sentryChange(), + ), + ), + ], + ), + ); + } + + void _showSigningVarsDialog({ + required BuildContext context, + required ProjectSettingsScreenState state, + bool toggleGenerateSigningKey = false, + }) { + showCupertinoModalPopup>( + context: context, + barrierDismissible: false, + builder: (ctx) => SigningDialog( + signingVars: state.config.signingVars, + ), + ).then( + (signingVars) { + if (!context.mounted) return; + bloc.add( + ProjectSettingsScreenEventSigningVarsChange( + signingVars: signingVars ?? state.config.signingVars, + ), + ); + if (toggleGenerateSigningKey) { + bloc.add( + ProjectSettingsScreenEventGenerateSigningKeyChange( + generateSigningKey: signingVars != null, + ), + ); + } + }, + ); + } +} diff --git a/lib/presentation/screen/project_settings_screen/widgets/right_part.dart b/lib/presentation/screen/project_settings_screen/widgets/right_part.dart new file mode 100644 index 00000000..add19b9d --- /dev/null +++ b/lib/presentation/screen/project_settings_screen/widgets/right_part.dart @@ -0,0 +1,151 @@ +import 'package:dropdown_button2/dropdown_button2.dart'; +import 'package:flutter/material.dart'; +import 'package:gap/gap.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/project_state_manager.dart'; +import 'package:onix_flutter_bricks/presentation/screen/project_settings_screen/bloc/project_settings_screen_bloc_imports.dart'; +import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; +import 'package:onix_flutter_bricks/presentation/widget/dialogs/dialog.dart'; +import 'package:onix_flutter_bricks/presentation/widget/inputs/labeled_segmented_control.dart'; +import 'package:onix_flutter_bricks/presentation/widget/inputs/switch_with_label.dart'; +import 'package:onix_flutter_bricks/util/enum/project_localization.dart'; +import 'package:onix_flutter_bricks/util/enum/project_router.dart'; +import 'package:onix_flutter_bricks/util/enum/project_theming.dart'; +import 'package:recase/recase.dart'; + +class RightPart extends StatelessWidget { + final ProjectSettingsScreenBloc bloc; + + const RightPart({ + required this.bloc, + super.key, + }); + + @override + Widget build(BuildContext context) { + final state = bloc.state; + return Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + border: Border.all(color: context.appColors.contrastColor), + borderRadius: BorderRadius.circular(10), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.only(right: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + S.of(context).stateManager, + style: context.appTextStyles.fs18?.copyWith( + color: context.appColors.textColor, + ), + ), + Material( + color: Colors.transparent, + child: DropdownButton2( + value: state.config.stateManager, + style: context.appTextStyles.fs18?.copyWith( + color: context.appColors.textColor, + ), + underline: const SizedBox(), + alignment: Alignment.centerRight, + items: ProjectStateManager.values + .map( + (e) => DropdownMenuItem( + value: e, + alignment: Alignment.centerRight, + child: Text(e.name.titleCase), + ), + ) + .toList(), + onChanged: (manager) { + if (manager != null) { + if (manager != state.config.stateManager && + state.config.screens.isNotEmpty && + !bloc.screensMatchStrategy(manager)) { + Dialogs.showOkCancelDialog( + context: context, + title: S.of(context).changeStateManagerError, + content: Text( + S.of(context).changeStateManagerErrorContent( + manager.strategy.variants.first.name, + ), + style: context.appTextStyles.fs18, + ), + onOk: () => _onStateManagerChange( + manager: manager, + bloc: bloc, + ), + ); + } else { + _onStateManagerChange(manager: manager, bloc: bloc); + } + } + }, + ), + ), + ], + ), + ), + const Gap(10), + LabeledSegmentedControl( + label: S.of(context).router, + values: ProjectRouter.values.map((e) => e.name).toList(), + onChange: (_) => + bloc.add(const ProjectSettingsScreenEventRouterChange()), + selectedValue: state.config.router.name, + ), + const Gap(20), + LabeledSegmentedControl( + label: S.of(context).localization, + values: ProjectLocalization.values.map((e) => e.name).toList(), + onChange: (_) => + bloc.add(const ProjectSettingsScreenEventLocalizationChange()), + selectedValue: state.config.localization.name, + ), + const Gap(20), + LabeledSegmentedControl( + label: S.of(context).theming, + values: ProjectTheming.values.map((e) => e.name).toList(), + onChange: (_) => + bloc.add(const ProjectSettingsScreenEventThemingChange()), + selectedValue: state.config.theming.name, + ), + const Gap(20), + SwitchWithLabel( + label: S.of(context).firebaseAuth, + initialValue: state.config.firebaseAuth, + valueSetter: (_) => + bloc.add(const ProjectSettingsScreenEventFirebaseChange()), + ), + if (!state.config.platformsList.webOnly) ...[ + const Gap(20), + SwitchWithLabel( + label: S.of(context).useScreenUtil, + initialValue: state.config.screenUtil, + valueSetter: (_) => bloc.add( + const ProjectSettingsScreenEvent.screenUtilChange(), + ), + ), + ], + ], + ), + ); + } + + void _onStateManagerChange({ + required ProjectStateManager manager, + required ProjectSettingsScreenBloc bloc, + }) { + bloc.add( + ProjectSettingsScreenEventStateManagerChange( + stateManager: manager, + ), + ); + } +} diff --git a/lib/presentation/screen/project_settings_screen/widgets/signing_dialog.dart b/lib/presentation/screen/project_settings_screen/widgets/signing_dialog.dart index 727838ef..18ba151c 100644 --- a/lib/presentation/screen/project_settings_screen/widgets/signing_dialog.dart +++ b/lib/presentation/screen/project_settings_screen/widgets/signing_dialog.dart @@ -1,6 +1,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; class SigningDialog extends StatefulWidget { @@ -17,17 +18,11 @@ class SigningDialog extends StatefulWidget { class _SigningDialogState extends State { final _nameController = TextEditingController(); - final _orgUnitController = TextEditingController(); - final _orgController = TextEditingController(); - final _cityController = TextEditingController(); - final _stateController = TextEditingController(); - final _countryController = TextEditingController(); - final _passwordController = TextEditingController(); bool _varsValid = true; @@ -81,7 +76,7 @@ class _SigningDialogState extends State { onChanged: (_) => _validate(), autofocus: true, inputFormatters: [ - FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9 ]')), + FilteringTextInputFormatter.allow(RegExp('[a-zA-Z0-9 ]')), ], ), const SizedBox(height: 15), @@ -100,7 +95,7 @@ class _SigningDialogState extends State { style: context.appTextStyles.fs18, onChanged: (_) => _validate(), inputFormatters: [ - FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9 ]')), + FilteringTextInputFormatter.allow(RegExp('[a-zA-Z0-9 ]')), ], ), const SizedBox(height: 15), @@ -119,7 +114,7 @@ class _SigningDialogState extends State { style: context.appTextStyles.fs18, onChanged: (_) => _validate(), inputFormatters: [ - FilteringTextInputFormatter.allow(RegExp(r'[-a-zA-Z0-9 ]')), + FilteringTextInputFormatter.allow(RegExp('[-a-zA-Z0-9 ]')), ], ), const SizedBox(height: 15), @@ -138,7 +133,7 @@ class _SigningDialogState extends State { style: context.appTextStyles.fs18, onChanged: (_) => _validate(), inputFormatters: [ - FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z ]')), + FilteringTextInputFormatter.allow(RegExp('[a-zA-Z ]')), ], ), const SizedBox(height: 15), @@ -157,7 +152,7 @@ class _SigningDialogState extends State { style: context.appTextStyles.fs18, onChanged: (_) => _validate(), inputFormatters: [ - FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z ]')), + FilteringTextInputFormatter.allow(RegExp('[a-zA-Z ]')), ], ), const SizedBox(height: 15), @@ -177,7 +172,7 @@ class _SigningDialogState extends State { onChanged: (_) => _validate(), inputFormatters: [ LengthLimitingTextInputFormatter(2), - FilteringTextInputFormatter.allow(RegExp(r'[A-Z ]')), + FilteringTextInputFormatter.allow(RegExp('[A-Z ]')), ], ), const SizedBox(height: 15), @@ -197,7 +192,9 @@ class _SigningDialogState extends State { style: context.appTextStyles.fs18, onChanged: (_) => _validate(), inputFormatters: [ - FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z\d ]')), + FilteringTextInputFormatter.allow( + AppConsts.digitsAndLatinWithSpaceOnly, + ), ], ), ], @@ -269,29 +266,39 @@ class _SigningDialogState extends State { }); } - Future _onOk(BuildContext context) async { - Navigator.pop(context, [ - _nameController.text.isNotEmpty - ? _nameController.text - : widget.signingVars[0], - _orgUnitController.text.isNotEmpty - ? _orgUnitController.text - : widget.signingVars[1], - _orgController.text.isNotEmpty - ? _orgController.text - : widget.signingVars[2], - _cityController.text.isNotEmpty - ? _cityController.text - : widget.signingVars[3], - _stateController.text.isNotEmpty - ? _stateController.text - : widget.signingVars[4], - _countryController.text.isNotEmpty - ? _countryController.text - : widget.signingVars[5], - _passwordController.text.isNotEmpty - ? _passwordController.text - : widget.signingVars[6], - ]); + void _onOk(BuildContext context) { + Navigator.pop( + context, + [ + if (_nameController.text.isNotEmpty) + _nameController.text + else + widget.signingVars[0], + if (_orgUnitController.text.isNotEmpty) + _orgUnitController.text + else + widget.signingVars[1], + if (_orgController.text.isNotEmpty) + _orgController.text + else + widget.signingVars[2], + if (_cityController.text.isNotEmpty) + _cityController.text + else + widget.signingVars[3], + if (_stateController.text.isNotEmpty) + _stateController.text + else + widget.signingVars[4], + if (_countryController.text.isNotEmpty) + _countryController.text + else + widget.signingVars[5], + if (_passwordController.text.isNotEmpty) + _passwordController.text + else + widget.signingVars[6], + ], + ); } } diff --git a/lib/presentation/screen/screens_screen/bloc/screens_screen_bloc.dart b/lib/presentation/screen/screens_screen/bloc/screens_screen_bloc.dart index 2e2068e2..da1bbbeb 100644 --- a/lib/presentation/screen/screens_screen/bloc/screens_screen_bloc.dart +++ b/lib/presentation/screen/screens_screen/bloc/screens_screen_bloc.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; import 'package:onix_flutter_bricks/core/di/repository.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/presentation/screen/screens_screen/bloc/screens_screen_bloc_imports.dart'; @@ -16,18 +16,20 @@ class ScreensScreenBloc on(_onScreenChangeInitial); } - FutureOr _onInit( + void _onInit( ScreensScreenEventInit event, Emitter emit, ) { - emit(state.copyWith( - config: event.config.copyWith( - screens: screenRepository.screens, + emit( + state.copyWith( + config: event.config.copyWith( + screens: screenRepository.screens, + ), ), - )); + ); } - FutureOr _onScreenAdd( + void _onScreenAdd( ScreensScreenEventOnScreenAdd event, Emitter emit, ) { @@ -36,47 +38,57 @@ class ScreensScreenBloc } else { screenRepository.addScreen(screen: event.screen); - emit(state.copyWith( - config: state.config.copyWith(screens: screenRepository.screens), - )); + emit( + state.copyWith( + config: state.config.copyWith(screens: screenRepository.screens), + ), + ); } } - FutureOr _onScreenDelete( + void _onScreenDelete( ScreensScreenEventOnScreenDelete event, Emitter emit, ) { screenRepository.removeScreen(screenName: event.screenName); - emit(state.copyWith( - config: state.config.copyWith(screens: screenRepository.screens), - )); + emit( + state.copyWith( + config: state.config.copyWith(screens: screenRepository.screens), + ), + ); } - FutureOr _onScreenModify( + void _onScreenModify( ScreensScreenEventOnScreenModify event, Emitter emit, ) { screenRepository.modifyScreen(event.screen, event.oldName); - emit(state.copyWith( + emit( + state.copyWith( config: state.config.copyWith( - screens: screenRepository.screens, - ))); + screens: screenRepository.screens, + ), + ), + ); } FutureOr _onScreenChangeInitial( ScreensScreenEventOnScreenChangeInitial event, Emitter emit, ) { - final oldInitial = state.config.screens.firstWhere((e) => e.initial); - oldInitial.initial = false; + final oldInitial = state.config.screens.firstWhere((e) => e.initial) + ..initial = false; screenRepository.modifyScreen(oldInitial, oldInitial.name); event.screen.initial = true; screenRepository.modifyScreen(event.screen, event.screen.name); - emit(state.copyWith( + emit( + state.copyWith( stateUpdate: state.stateUpdate + 1, config: state.config.copyWith( screens: screenRepository.screens, - ))); + ), + ), + ); } } diff --git a/lib/presentation/screen/screens_screen/screens_screen.dart b/lib/presentation/screen/screens_screen/screens_screen.dart index 59cf0a50..ef7e642b 100644 --- a/lib/presentation/screen/screens_screen/screens_screen.dart +++ b/lib/presentation/screen/screens_screen/screens_screen.dart @@ -1,11 +1,12 @@ import 'package:collection/collection.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_block_state.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/domain/entity/screen/screen.dart'; import 'package:onix_flutter_bricks/presentation/screen/screens_screen/bloc/screens_screen_bloc_imports.dart'; @@ -33,38 +34,50 @@ class ScreensScreen extends StatefulWidget { class _ScreensScreenState extends BaseState { + @override + ScreensScreenBloc createBloc() => GetIt.I.get(); + @override Widget buildWidget(BuildContext context) { return srObserver( context: context, - child: blocBuilder(builder: (context, state) { - return CupertinoPageScaffold( - navigationBar: TitleBar( - title: S.of(context).selectProjectScreens, - actions: [ - AppFilledButton( - label: S.of(context).addScreen, - icon: Icons.add, - onPressed: () => showCupertinoModalPopup( - context: context, - barrierDismissible: false, - builder: (context) => const AddScreenDialog(), - ).then((screen) { - if (screen != null) { - if (state.config.screens.isEmpty) { - screen.initial = true; - } - blocOf(context).add( - ScreensScreenEventOnScreenAdd(screen: screen), - ); - } - }), - ), - ], - ), - child: _buildMainContainer(context, state), - ); - }), + child: blocBuilder( + builder: (context, state) { + return CupertinoPageScaffold( + navigationBar: TitleBar( + title: S.of(context).selectProjectScreens, + actions: [ + AppFilledButton( + label: S.of(context).addScreen, + icon: Icons.add, + onPressed: () => showCupertinoModalPopup( + context: context, + barrierDismissible: false, + builder: (context) => AddScreenDialog( + stateManagers: + state.config.stateManager.strategy.variants, + ), + ).then( + (screen) { + if (!context.mounted) return; + + if (screen != null) { + if (state.config.screens.isEmpty) { + screen.initial = true; + } + blocOf(context).add( + ScreensScreenEventOnScreenAdd(screen: screen), + ); + } + }, + ), + ), + ], + ), + child: _buildMainContainer(context, state), + ); + }, + ), onSR: _onSingleResult, ); } @@ -82,10 +95,12 @@ class _ScreensScreenState extends BaseState a.name.compareTo(b.name)) .toSet(), + stateManagers: state.config.stateManager.strategy.variants, onModifyScreen: (screen, name) => blocOf(context).add( ScreensScreenEventOnScreenModify( - screen: screen, oldName: name), + screen: screen, + oldName: name, + ), ), onDeleteScreen: (screen) => blocOf(context).add( ScreensScreenEventOnScreenDelete( @@ -162,7 +180,7 @@ class _ScreensScreenState extends BaseState stateManagers; const AddScreenDialog({ + required this.stateManagers, this.screen, super.key, }); @@ -22,7 +29,8 @@ class AddScreenDialog extends StatefulWidget { class _AddScreenDialogState extends State { final TextEditingController _screenNameController = TextEditingController(); - ScreenStateManager _stateManagement = ScreenStateManager.none; + StateManagementVariant _stateManagement = + const StatelessStateManagementVariant(); final _dialogFocusNode = FocusNode(); final _textFieldFocusNode = FocusNode(); @@ -35,7 +43,9 @@ class _AddScreenDialogState extends State { _currentFocusNode.requestFocus(); if (widget.screen != null) { _screenNameController.text = widget.screen!.name; - _stateManagement = widget.screen!.stateManager; + _stateManagement = widget.screen!.stateVariant; + } else { + _stateManagement = widget.stateManagers.first; } super.initState(); } @@ -70,49 +80,53 @@ class _AddScreenDialogState extends State { content: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - CupertinoTextField( - controller: _screenNameController, - focusNode: _textFieldFocusNode, - style: context.appTextStyles.fs18, - onTap: () { - setState(() { - _currentFocusNode = _textFieldFocusNode; - _textFieldFocusNode.requestFocus(); - }); - }, - onSubmitted: (_) => _onOk(context), - placeholder: S.of(context).screenName, - inputFormatters: [ - FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')), + Row( + children: [ + Expanded( + child: CupertinoTextField( + controller: _screenNameController, + focusNode: _textFieldFocusNode, + style: context.appTextStyles.fs18, + onTap: () { + setState(() { + _currentFocusNode = _textFieldFocusNode; + _textFieldFocusNode.requestFocus(); + }); + }, + onSubmitted: (_) => _onOk(context), + placeholder: S.of(context).screenName, + inputFormatters: [ + const FirstCharacterNotDigitFormatter(), + FilteringTextInputFormatter.allow( + AppConsts.digitsAndLatinLetters, + ), + ], + ), + ), + const SizedBox(width: 12), + TooltipWrapper( + message: S.of(context).screenClassNameHelperText, + ), ], ), - const SizedBox(height: 15), - LabeledCheckbox( - focused: _currentFocusNode == _dialogFocusNode, - label: S.of(context).usingBloc, - initialValue: _stateManagement == ScreenStateManager.bloc, - onAction: () { - setState(() { - if (_stateManagement == ScreenStateManager.bloc) { - _stateManagement = ScreenStateManager.none; - } else { - _stateManagement = ScreenStateManager.bloc; - } - }); - }, - ), - LabeledCheckbox( - focused: _currentFocusNode == _dialogFocusNode, - label: S.of(context).usingCubit, - initialValue: _stateManagement == ScreenStateManager.cubit, - onAction: () { - setState(() { - if (_stateManagement == ScreenStateManager.cubit) { - _stateManagement = ScreenStateManager.none; - } else { - _stateManagement = ScreenStateManager.cubit; - } - }); + const Gap(15), + ...widget.stateManagers.map( + (stateManager) { + return LabeledCheckbox( + focused: _currentFocusNode == _dialogFocusNode, + label: stateManager.name, + initialValue: _stateManagement == stateManager, + mainAxisAlignment: MainAxisAlignment.start, + onAction: () { + setState( + () { + if (_stateManagement != stateManager) { + _stateManagement = stateManager; + } + }, + ); + }, + ); }, ), ], @@ -135,28 +149,39 @@ class _AddScreenDialogState extends State { ); } - Future _onOk(BuildContext context) async { + void _onOk(BuildContext context) { if (_screenNameController.text.isNotEmpty) { - String screenName = _screenNameController.text.pascalCase; + var screenName = _screenNameController.text.pascalCase; while (screenName.endsWith('Screen')) { screenName = screenName.replaceLast('Screen', ''); } - if (widget.screen != null) { - widget.screen!.name = screenName; - widget.screen!.stateManager = _stateManagement; - Navigator.pop(context, widget.screen); + final screen = widget.screen; + if (screen != null) { + screen + ..name = screenName + ..stateVariant = _stateManagement; + Navigator.pop(context, screen); } else { Navigator.pop( - context, - Screen( - name: screenName, - stateManager: _stateManagement, - exists: false)); + context, + Screen( + name: screenName, + stateVariant: _stateManagement, + ), + ); } } else { Navigator.pop(context); } } + + @override + void dispose() { + _screenNameController.dispose(); + _dialogFocusNode.dispose(); + _textFieldFocusNode.dispose(); + super.dispose(); + } } diff --git a/lib/presentation/screen/screens_screen/widgets/figma_styles_dialog/bloc/figma_styles_dialog_bloc.dart b/lib/presentation/screen/screens_screen/widgets/figma_styles_dialog/bloc/figma_styles_dialog_bloc.dart index e39cf60e..14422fdc 100644 --- a/lib/presentation/screen/screens_screen/widgets/figma_styles_dialog/bloc/figma_styles_dialog_bloc.dart +++ b/lib/presentation/screen/screens_screen/widgets/figma_styles_dialog/bloc/figma_styles_dialog_bloc.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_color_style.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_text_style.dart'; import 'package:onix_flutter_bricks/domain/usecase/styles/get_figma_styles_usecase.dart'; @@ -16,7 +16,7 @@ class FigmaStylesDialogBloc extends BaseBloc(_onInit); } - FutureOr _onInit( + Future _onInit( FigmaStylesEventInit event, Emitter emit, ) async { @@ -39,7 +39,6 @@ class FigmaStylesDialogBloc extends BaseBloc { + @override + FigmaStylesDialogBloc createBloc() => GetIt.I.get(); + @override void onBlocCreated(BuildContext context, FigmaStylesDialogBloc bloc) { bloc.add( FigmaStylesDialogEvent.getStyles( - figmaId: widget.figmaFile, token: widget.figmaToken), + figmaId: widget.figmaFile, + token: widget.figmaToken, + ), ); super.onBlocCreated(context, bloc); } @@ -40,107 +46,110 @@ class _FigmaStylesDialogState extends BaseState Text( - dataState.textStyles[index].name.sentenceCase, - style: dataState.textStyles[index].getFontStyle(), + SliverList.builder( + itemBuilder: (context, index) => Text( + dataState.textStyles[index].name.sentenceCase, + style: dataState.textStyles[index].getFontStyle(), + ), + itemCount: dataState.textStyles.length, ), - itemCount: dataState.textStyles.length, - ), - const SliverToBoxAdapter( - child: Delimiter.height(20), - ) - ], + const SliverToBoxAdapter( + child: Delimiter.height(20), + ), + ], + ), ), ), - ), - SizedBox( - height: 1, - width: double.infinity, - child: ColoredBox( - color: context.appColors.fadedColor, + SizedBox( + height: 1, + width: double.infinity, + child: ColoredBox( + color: context.appColors.fadedColor, + ), ), - ), - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Expanded( - child: AppActionButton( - label: S.of(context).ok, - onPressed: () => context.pop( - [dataState.textStyles, dataState..colorStyles], + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Expanded( + child: AppActionButton( + label: S.of(context).ok, + onPressed: () => context.pop( + [dataState.textStyles, dataState..colorStyles], + ), ), ), - ), - SizedBox( - height: 55, - width: 1, - child: ColoredBox( - color: context.appColors.fadedColor, + SizedBox( + height: 55, + width: 1, + child: ColoredBox( + color: context.appColors.fadedColor, + ), ), - ), - Expanded( - child: AppActionButton( - label: S.of(context).cancel, - onPressed: () { - context.pop(); - }, + Expanded( + child: AppActionButton( + label: S.of(context).cancel, + onPressed: () { + context.pop(); + }, + ), ), - ), - ], - ), - ], - ), - ); - }), + ], + ), + ], + ), + ); + }, + ), ), ); } diff --git a/lib/presentation/screen/screens_screen/widgets/figma_styles_dialog/widget/color_styles_wrap.dart b/lib/presentation/screen/screens_screen/widgets/figma_styles_dialog/widget/color_styles_wrap.dart index a83aecb2..e633d1ca 100644 --- a/lib/presentation/screen/screens_screen/widgets/figma_styles_dialog/widget/color_styles_wrap.dart +++ b/lib/presentation/screen/screens_screen/widgets/figma_styles_dialog/widget/color_styles_wrap.dart @@ -13,30 +13,31 @@ class ColorStylesWrap extends StatelessWidget { @override Widget build(BuildContext context) { return Wrap( - spacing: 10, - runSpacing: 10, - alignment: WrapAlignment.center, - runAlignment: WrapAlignment.center, - crossAxisAlignment: WrapCrossAlignment.center, - children: List.generate( - styles.length, - (index) => Container( - width: 100, - height: 100, - padding: const EdgeInsets.all(10), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(10), + spacing: 10, + runSpacing: 10, + alignment: WrapAlignment.center, + runAlignment: WrapAlignment.center, + crossAxisAlignment: WrapCrossAlignment.center, + children: List.generate( + styles.length, + (index) => Container( + width: 100, + height: 100, + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + color: styles[index].color, + ), + alignment: Alignment.center, + child: Text( + styles[index].name.sentenceCase.toLowerCase(), + textAlign: TextAlign.center, + style: TextStyle( color: styles[index].color, ), - alignment: Alignment.center, - child: Text( - styles[index].name.sentenceCase.toLowerCase(), - textAlign: TextAlign.center, - style: TextStyle( - color: styles[index].color, - ), - ), ), - )); + ), + ), + ); } } diff --git a/lib/presentation/screen/screens_screen/widgets/screen_table.dart b/lib/presentation/screen/screens_screen/widgets/screen_table.dart index b3d9ec9a..abddcbf6 100644 --- a/lib/presentation/screen/screens_screen/widgets/screen_table.dart +++ b/lib/presentation/screen/screens_screen/widgets/screen_table.dart @@ -1,7 +1,8 @@ import 'package:flutter/cupertino.dart'; import 'package:msh_checkbox/msh_checkbox.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; import 'package:onix_flutter_bricks/domain/entity/screen/screen.dart'; +import 'package:onix_flutter_bricks/domain/entity/state_management/state_management_variant.dart'; import 'package:onix_flutter_bricks/presentation/screen/screens_screen/widgets/add_screen_dialog.dart'; import 'package:onix_flutter_bricks/presentation/screen/screens_screen/widgets/screen_table_cell.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; @@ -9,12 +10,14 @@ import 'package:recase/recase.dart'; class ScreenTable extends StatelessWidget { final Set screens; - final Function(Screen, String) onModifyScreen; - final Function(Screen) onDeleteScreen; - final Function(Screen) onChangeInitial; + final List stateManagers; + final void Function(Screen, String) onModifyScreen; + final void Function(Screen) onDeleteScreen; + final void Function(Screen) onChangeInitial; const ScreenTable({ required this.screens, + required this.stateManagers, required this.onModifyScreen, required this.onDeleteScreen, required this.onChangeInitial, @@ -33,9 +36,8 @@ class ScreenTable extends StatelessWidget { color: context.appColors.fadedColor, strokeAlign: BorderSide.strokeAlignOutside, ), - borderRadius: const BorderRadius.only( - topLeft: Radius.circular(10), - topRight: Radius.circular(10), + borderRadius: const BorderRadius.vertical( + top: Radius.circular(10), ), ), child: Row( @@ -97,7 +99,6 @@ class ScreenTable extends StatelessWidget { border: Border( bottom: BorderSide( color: context.appColors.fadedColor, - width: 1, ), ), ), @@ -125,19 +126,21 @@ class ScreenTable extends StatelessWidget { value: Text( '${screen.name.pascalCase}Screen', style: context.appTextStyles.fs18?.copyWith( - color: screen.exists - ? context.appColors.fadedColor - : context.appColors.textColor), + color: screen.exists + ? context.appColors.fadedColor + : context.appColors.textColor, + ), ), decorated: true, ), Cell( value: Text( - screen.stateManager.name.pascalCase, + screen.stateVariant.name, style: context.appTextStyles.fs18?.copyWith( - color: screen.exists - ? context.appColors.fadedColor - : context.appColors.textColor), + color: screen.exists + ? context.appColors.fadedColor + : context.appColors.textColor, + ), ), decorated: true, ), @@ -145,7 +148,7 @@ class ScreenTable extends StatelessWidget { value: SizedBox( height: 45, child: Padding( - padding: const EdgeInsets.symmetric(vertical: 8.0), + padding: const EdgeInsets.symmetric(vertical: 8), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ @@ -154,26 +157,34 @@ class ScreenTable extends StatelessWidget { ? context.appColors.fadedColor : context.appColors.textColor, padding: const EdgeInsets.symmetric( - horizontal: 10), + horizontal: 10, + ), onPressed: () { if (!screen.exists) { showCupertinoModalPopup( context: context, barrierDismissible: false, builder: (context) => AddScreenDialog( - screen: Screen.copyOf(screen)), - ).then((modifiedScreen) { - if (modifiedScreen != null) { - onModifyScreen( - modifiedScreen, screen.name); - } - }); + screen: Screen.copyOf(screen), + stateManagers: stateManagers, + ), + ).then( + (modifiedScreen) { + if (modifiedScreen != null) { + onModifyScreen( + modifiedScreen, + screen.name, + ); + } + }, + ); } }, child: Text( S.of(context).modify, style: context.appTextStyles.fs18?.copyWith( - color: context.appColors.darkColor), + color: context.appColors.darkColor, + ), ), ), const SizedBox(width: 10), @@ -182,7 +193,8 @@ class ScreenTable extends StatelessWidget { ? context.appColors.fadedColor : context.appColors.textColor, padding: const EdgeInsets.symmetric( - horizontal: 10), + horizontal: 10, + ), onPressed: () { if (!screen.exists) { onDeleteScreen(screen); diff --git a/lib/presentation/screen/screens_screen/widgets/screen_table_cell.dart b/lib/presentation/screen/screens_screen/widgets/screen_table_cell.dart index fc322a3c..f7e2e3f7 100644 --- a/lib/presentation/screen/screens_screen/widgets/screen_table_cell.dart +++ b/lib/presentation/screen/screens_screen/widgets/screen_table_cell.dart @@ -23,7 +23,6 @@ class Cell extends StatelessWidget { border: Border( right: BorderSide( color: context.appColors.fadedColor, - width: 1, ), ), ) diff --git a/lib/presentation/screen/splash_screen/bloc/splash_screen_bloc.dart b/lib/presentation/screen/splash_screen/bloc/splash_screen_bloc.dart index 1fb350fb..44c6fcda 100644 --- a/lib/presentation/screen/splash_screen/bloc/splash_screen_bloc.dart +++ b/lib/presentation/screen/splash_screen/bloc/splash_screen_bloc.dart @@ -3,7 +3,7 @@ import 'dart:convert'; import 'dart:io'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; import 'package:onix_flutter_bricks/core/di/app.dart'; import 'package:onix_flutter_bricks/presentation/screen/splash_screen/bloc/splash_screen_bloc_imports.dart'; import 'package:onix_flutter_bricks/util/extension/version_extension.dart'; @@ -17,14 +17,14 @@ class SplashScreenBloc add(const SplashScreenEvent.init()); } - FutureOr _onInit( + Future _onInit( SplashScreenEventInit event, Emitter emit, ) async { emit(state.copyWith(logoVisible: true)); } - FutureOr _onAnimationFinished( + Future _onAnimationFinished( SplashScreenEventOnAnimationFinished event, Emitter emit, ) async { @@ -32,9 +32,9 @@ class SplashScreenBloc final localVersion = packageInfo.version; - var mainProcess = await Process.start('zsh', []); + final mainProcess = await Process.start('zsh', []); - String remoteVersion = ''; + var remoteVersion = ''; mainProcess.stdout.transform(utf8.decoder).listen((event) { if (event.contains('version: ')) { @@ -43,11 +43,12 @@ class SplashScreenBloc } }); - mainProcess.stdin.writeln('source \$HOME/.zshrc'); - mainProcess.stdin.writeln('source \$HOME/.bash_profile'); + mainProcess.stdin.writeln(r'source $HOME/.zshrc'); + mainProcess.stdin.writeln(r'source $HOME/.bash_profile'); mainProcess.stdin.writeln( - 'curl https://raw.githubusercontent.com/Onix-Systems/onix-flutter-project-generator/main/pubspec.yaml | grep version && exit'); + 'curl https://raw.githubusercontent.com/Onix-Systems/onix-flutter-project-generator/main/pubspec.yaml | grep version && exit', + ); await mainProcess.exitCode; @@ -68,9 +69,11 @@ class SplashScreenBloc } } - emit(state.copyWith( - remoteVersion: remoteVersion, - localVersion: localVersion, - )); + emit( + state.copyWith( + remoteVersion: remoteVersion, + localVersion: localVersion, + ), + ); } } diff --git a/lib/presentation/screen/splash_screen/splash_screen.dart b/lib/presentation/screen/splash_screen/splash_screen.dart index 3fbf035c..7965a272 100644 --- a/lib/presentation/screen/splash_screen/splash_screen.dart +++ b/lib/presentation/screen/splash_screen/splash_screen.dart @@ -3,11 +3,12 @@ import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; +import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_block_state.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/presentation/screen/splash_screen/bloc/splash_screen_bloc_imports.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; @@ -25,14 +26,17 @@ class SplashScreen extends StatefulWidget { class _SplashScreenState extends BaseState { + @override + SplashScreenBloc createBloc() => GetIt.I.get(); + @override Widget buildWidget(BuildContext context) { return srObserver( context: context, child: CupertinoPageScaffold( child: SizedBox.expand( - child: blocConsumer( - stateListener: (state) => _buildMainContainer(context, state), + child: blocBuilder( + builder: _buildMainContainer, ), ), ), @@ -108,7 +112,7 @@ class _SplashScreenState extends BaseState(_onInit); } - FutureOr _onInit( + void _onInit( SummaryScreenEventInit event, Emitter emit, ) { - emit(state.copyWith( + emit( + state.copyWith( config: event.config.copyWith( - screens: screenRepository.screens, - ))); + screens: screenRepository.screens, + ), + ), + ); } } diff --git a/lib/presentation/screen/summary_screen/summary_screen.dart b/lib/presentation/screen/summary_screen/summary_screen.dart index 4c6b9d19..d2ea8e1c 100644 --- a/lib/presentation/screen/summary_screen/summary_screen.dart +++ b/lib/presentation/screen/summary_screen/summary_screen.dart @@ -1,12 +1,13 @@ import 'package:collection/collection.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_block_state.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/presentation/screen/generation_screen/generation_screen.dart'; import 'package:onix_flutter_bricks/presentation/screen/summary_screen/bloc/summary_screen_bloc_imports.dart'; @@ -30,14 +31,17 @@ class SummaryScreen extends StatefulWidget { class _SummaryScreenState extends BaseState { + @override + SummaryScreenBloc createBloc() => GetIt.I.get(); + @override Widget buildWidget(BuildContext context) { return CupertinoPageScaffold( navigationBar: TitleBar( title: S.of(context).summary, ), - child: blocConsumer( - stateListener: (state) => _buildMainContainer(context, state), + child: blocBuilder( + builder: _buildMainContainer, ), ); } @@ -54,11 +58,7 @@ class _SummaryScreenState extends BaseState a.name.compareTo(b.name)) - .map((e) => - '{name: ${e.name.pascalCase}Screen, bloc: ${e.stateManager}, initial: ${e.initial}}') + .map( + (e) => 'name: ${e.name.pascalCase}Screen, type:' + ' ${e.stateVariant.name},' + ' initial: ${e.initial}', + ) .join(',\n'), ), if (state.config.swaggerUrl.isNotEmpty) @@ -146,26 +153,10 @@ class _SummaryScreenState extends BaseState a.name.compareTo(b.name)) - .map((e) => - '${e.name.pascalCase}(${e.dataComponentsNames.sorted((a, b) => a.compareTo(b)).map((e) => e.pascalCase).join(', ')})') - .join('\n\n'), - ),*/ - //Todo Resolve - /*if (state.config.dataComponents.isNotEmpty) - SummaryCell( - variable: S.of(context).dataComponents, - value: state.config.dataComponents - .toList() - .sorted((a, b) => a.name.compareTo(b.name)) - .map((e) => e.name.pascalCase) - .join(', ')),*/ + SummaryCell( + variable: S.of(context).integrateSentry, + value: state.config.sentry.toString(), + ), if (state.config.styles.isNotEmpty) SummaryStylesCell( variable: 'Styles', diff --git a/lib/presentation/screen/summary_screen/widgets/summary_cell.dart b/lib/presentation/screen/summary_screen/widgets/summary_cell.dart index 2645a965..d3f36214 100644 --- a/lib/presentation/screen/summary_screen/widgets/summary_cell.dart +++ b/lib/presentation/screen/summary_screen/widgets/summary_cell.dart @@ -13,7 +13,7 @@ class SummaryCell extends StatelessWidget { @override Widget build(BuildContext context) { - return Container( + return DecoratedBox( decoration: BoxDecoration( border: Border.all( color: context.appColors.darkContrastColor, diff --git a/lib/presentation/screen/summary_screen/widgets/summary_styles_cell.dart b/lib/presentation/screen/summary_screen/widgets/summary_styles_cell.dart index d78922f4..e3d7a102 100644 --- a/lib/presentation/screen/summary_screen/widgets/summary_styles_cell.dart +++ b/lib/presentation/screen/summary_screen/widgets/summary_styles_cell.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_color_style.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_styles.dart'; import 'package:onix_flutter_bricks/domain/entity/app_styles/app_text_style.dart'; @@ -17,7 +17,7 @@ class SummaryStylesCell extends StatelessWidget { @override Widget build(BuildContext context) { - return Container( + return DecoratedBox( decoration: BoxDecoration( border: Border.all( color: context.appColors.contrastColor, @@ -71,7 +71,10 @@ class SummaryStylesCell extends StatelessWidget { .toList() .map( (e) => Text( - '${e.name}: ${e.fontFamily}, size: ${e.fontSize}, weight: ${e.fontWeight}, letterSpacing: ${e.letterSpacing.toStringAsFixed(2)}', + '${e.name}: ${e.fontFamily}, size: ${e.fontSize},' + ' weight: ${e.fontWeight}, ' + 'letterSpacing:' + ' ${e.letterSpacing.toStringAsFixed(2)}', style: context.appTextStyles.fs18, ), ) diff --git a/lib/presentation/screen/swagger_parser_screen/bloc/swagger_parser_screen_bloc.dart b/lib/presentation/screen/swagger_parser_screen/bloc/swagger_parser_screen_bloc.dart index 3c15f5cd..9a35d974 100644 --- a/lib/presentation/screen/swagger_parser_screen/bloc/swagger_parser_screen_bloc.dart +++ b/lib/presentation/screen/swagger_parser_screen/bloc/swagger_parser_screen_bloc.dart @@ -1,43 +1,41 @@ import 'dart:async'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_bloc.dart'; -import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/domain/usecase/swagger/empty_swagger_components_usecase.dart'; import 'package:onix_flutter_bricks/domain/usecase/swagger/fetch_swagger_data_usecase.dart'; import 'package:onix_flutter_bricks/presentation/screen/swagger_parser_screen/bloc/swagger_parser_screen_bloc_imports.dart'; class SwaggerParserScreenBloc extends BaseBloc { final FetchSwaggerDataUseCase _fetchSwaggerDataUseCase; + final ClearSwaggerComponentsUseCase _clearSwaggerComponentsUseCase; - SwaggerParserScreenBloc(this._fetchSwaggerDataUseCase) - : super( - const SwaggerParserScreenStateData(config: Config()), - ) { + SwaggerParserScreenBloc( + this._fetchSwaggerDataUseCase, + this._clearSwaggerComponentsUseCase, + ) : super(const SwaggerParserScreenStateData()) { on(_onInit); on(_onParse); } - FutureOr _onInit( + void _onInit( SwaggerParserScreenEventInit event, Emitter emit, ) { emit(state.copyWith(config: event.config)); } - FutureOr _onParse( + Future _onParse( SwaggerParserScreenEventParse event, Emitter emit, ) async { if (event.url.isEmpty) { + emit(state.copyWith(config: state.config.copyWith(swaggerUrl: ''))); + _clearSwaggerComponentsUseCase(); addSr(const SwaggerParserScreenSR.onContinue()); + return; } - emit(state.copyWith( - config: state.config.copyWith( - swaggerUrl: event.url, - ), - )); - showProgress(); final swaggerComponentsResult = @@ -45,6 +43,13 @@ class SwaggerParserScreenBloc extends BaseBloc class _$SwaggerParserScreenStateDataImpl implements SwaggerParserScreenStateData { - const _$SwaggerParserScreenStateDataImpl({required this.config}); + const _$SwaggerParserScreenStateDataImpl({this.config = const Config()}); @override + @JsonKey() final Config config; @override @@ -850,7 +851,7 @@ class _$SwaggerParserScreenStateDataImpl abstract class SwaggerParserScreenStateData implements SwaggerParserScreenState { - const factory SwaggerParserScreenStateData({required final Config config}) = + const factory SwaggerParserScreenStateData({final Config config}) = _$SwaggerParserScreenStateDataImpl; @override diff --git a/lib/presentation/screen/swagger_parser_screen/swagger_parser_screen.dart b/lib/presentation/screen/swagger_parser_screen/swagger_parser_screen.dart index 7d0c5625..148a5467 100644 --- a/lib/presentation/screen/swagger_parser_screen/swagger_parser_screen.dart +++ b/lib/presentation/screen/swagger_parser_screen/swagger_parser_screen.dart @@ -1,9 +1,10 @@ import 'package:flutter/cupertino.dart'; +import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; -import 'package:onix_flutter_bricks/core/arch/bloc/base_block_state.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; -import 'package:onix_flutter_bricks/core/router/app_router.dart'; +import 'package:onix_flutter_bloc/onix_flutter_bloc.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/router/app_router.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/presentation/screen/swagger_parser_screen/bloc/swagger_parser_screen_bloc_imports.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; @@ -28,42 +29,45 @@ class _SwaggerParserScreenState extends BaseState { final TextEditingController _urlController = TextEditingController(); + @override + SwaggerParserScreenBloc createBloc() => + GetIt.I.get(); + @override void onBlocCreated(BuildContext context, SwaggerParserScreenBloc bloc) { - bloc.add(SwaggerParserScreenEventInit(config: widget.config)); + bloc.add(SwaggerParserScreenEvent.init(config: widget.config)); _urlController.text = widget.config.swaggerUrl; super.onBlocCreated(context, bloc); } @override Widget buildWidget(BuildContext context) { - return srObserver( - context: context, - child: CupertinoPageScaffold( - navigationBar: TitleBar( - title: S.of(context).importApi, - ), - child: SizedBox.expand( - child: blocConsumer( - stateListener: (state) => _buildMainContainer(context, state), - ), + return CupertinoPageScaffold( + navigationBar: TitleBar( + title: S.of(context).importApi, + ), + child: SizedBox.expand( + child: blocBuilder( + builder: _buildMainContainer, ), ), - onSR: _onSingleResult, ); } - void _onSingleResult( - BuildContext context, SwaggerParserScreenSR singleResult) { - singleResult.when( + @override + void onSR(BuildContext context, SwaggerParserScreenSR sr) { + super.onSR(context, sr); + sr.when( onParseError: () => Dialogs.showOkDialog( context: context, isError: true, title: S.of(context).error, - content: Text(S.of(context).parseErrorMessage, - style: context.appTextStyles.fs18?.copyWith( - fontSize: 16, - )), + content: Text( + S.of(context).parseErrorMessage, + style: context.appTextStyles.fs18?.copyWith( + fontSize: 16, + ), + ), ), onContinue: () { _urlController.clear(); @@ -96,7 +100,7 @@ class _SwaggerParserScreenState extends BaseState _onContinue(context, state), + onEditingComplete: () => _processSwaggerParser(context), expanded: true, ), ), @@ -104,12 +108,8 @@ class _SwaggerParserScreenState extends BaseState _processSwaggerParser(context), + onPrevPressed: () => _onBack(context, state), ), ], ), @@ -117,27 +117,25 @@ class _SwaggerParserScreenState extends BaseState + void _onContinue(BuildContext context, SwaggerParserScreenState state) { + state.config.projectExists + ? context.pop( + widget.config.copyWith( + swaggerUrl: state.config.swaggerUrl, + ), + ) + : context.go( + AppRouter.dataComponentsScreen, + extra: state.config, + ); + } + + void _onBack(BuildContext context, SwaggerParserScreenState state) => state.config.projectExists ? context.pop( widget.config.copyWith( @@ -146,8 +144,6 @@ class _SwaggerParserScreenState extends BaseState { : context.appColors.fadedColor, foregroundColor: _defaultColor, shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(5), - side: focused - ? BorderSide( - color: _defaultColor.withOpacity(0.7), - width: 2, - ) - : BorderSide.none), + borderRadius: BorderRadius.circular(5), + side: focused + ? BorderSide( + color: _defaultColor.withOpacity(0.7), + width: 2, + ) + : BorderSide.none, + ), padding: widget.padding ?? const EdgeInsets.symmetric( horizontal: 20, @@ -89,12 +90,13 @@ class _AppFilledButtonState extends State { color: hovered ? widget.color ?? _defaultColor : _textColor(), ), - Text(widget.label, - style: context.appTextStyles.fs18?.copyWith( - color: hovered - ? widget.color ?? _defaultColor - : _textColor(), - )), + Text( + widget.label, + style: context.appTextStyles.fs18?.copyWith( + color: + hovered ? widget.color ?? _defaultColor : _textColor(), + ), + ), ], ) : Row( @@ -109,12 +111,13 @@ class _AppFilledButtonState extends State { ), const Delimiter.width(10), ], - Text(widget.label, - style: context.appTextStyles.fs18?.copyWith( - color: hovered - ? widget.color ?? _defaultColor - : _textColor(), - )), + Text( + widget.label, + style: context.appTextStyles.fs18?.copyWith( + color: + hovered ? widget.color ?? _defaultColor : _textColor(), + ), + ), if (widget.icon != null && !widget.iconLeft) ...[ const Delimiter.width(10), Icon( diff --git a/lib/presentation/widget/buttons/navigation_button_bar.dart b/lib/presentation/widget/buttons/navigation_button_bar.dart index 5b2c681b..9b8cfbe8 100644 --- a/lib/presentation/widget/buttons/navigation_button_bar.dart +++ b/lib/presentation/widget/buttons/navigation_button_bar.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import 'package:onix_flutter_bricks/core/arch/widget/common/misk.dart'; +import 'package:onix_flutter_bricks/app/widget/common/misk.dart'; import 'package:onix_flutter_bricks/presentation/widget/buttons/app_filled_button.dart'; class NavigationButtonBar extends StatelessWidget { @@ -26,7 +26,6 @@ class NavigationButtonBar extends StatelessWidget { Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.end, - crossAxisAlignment: CrossAxisAlignment.center, children: [ AppFilledButton( label: prevText, @@ -41,7 +40,7 @@ class NavigationButtonBar extends StatelessWidget { icon: nextIcon ?? Icons.arrow_forward_ios_rounded, iconLeft: false, onPressed: onNextPressed, - ) + ), ], ); } diff --git a/lib/presentation/widget/buttons/remove_button.dart b/lib/presentation/widget/buttons/remove_button.dart index a11a7673..c5a2d6d5 100644 --- a/lib/presentation/widget/buttons/remove_button.dart +++ b/lib/presentation/widget/buttons/remove_button.dart @@ -19,7 +19,7 @@ class RemoveButton extends StatelessWidget { color: context.appColors.controlColor, splashRadius: 20, style: IconButton.styleFrom( - padding: const EdgeInsets.all(0), + padding: EdgeInsets.zero, shape: const CircleBorder(), ), onPressed: onPressed, diff --git a/lib/presentation/widget/colored_line.dart b/lib/presentation/widget/colored_line.dart index 9392b9bf..e02f13de 100644 --- a/lib/presentation/widget/colored_line.dart +++ b/lib/presentation/widget/colored_line.dart @@ -6,8 +6,8 @@ class ColoredLine extends StatelessWidget { final OutputLine line; const ColoredLine({ - super.key, required this.line, + super.key, }); @override diff --git a/lib/presentation/widget/dialogs/dialog.dart b/lib/presentation/widget/dialogs/dialog.dart index 4c0e8e5f..30149887 100644 --- a/lib/presentation/widget/dialogs/dialog.dart +++ b/lib/presentation/widget/dialogs/dialog.dart @@ -1,6 +1,6 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; class Dialogs { @@ -37,13 +37,13 @@ class Dialogs { ); } - static showOkCancelDialog({ + static void showOkCancelDialog({ required BuildContext context, + required Widget content, bool isError = false, String title = '', String? okLabel, String? cancelLabel, - required Widget content, VoidCallback? onOk, VoidCallback? onCancel, }) { @@ -97,11 +97,11 @@ class Dialogs { ); } - static showYesNoCancelDialog({ + static void showYesNoCancelDialog({ required BuildContext context, + required Widget content, bool isError = false, String title = '', - required Widget content, VoidCallback? onYes, VoidCallback? onNo, VoidCallback? onCancel, diff --git a/lib/presentation/widget/inputs/labeled_checkbox.dart b/lib/presentation/widget/inputs/labeled_checkbox.dart index 819a2d2b..03fbcc61 100644 --- a/lib/presentation/widget/inputs/labeled_checkbox.dart +++ b/lib/presentation/widget/inputs/labeled_checkbox.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:gap/gap.dart'; import 'package:msh_checkbox/msh_checkbox.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; @@ -8,6 +9,7 @@ class LabeledCheckbox extends StatelessWidget { final VoidCallback onAction; final bool disabled; final bool focused; + final MainAxisAlignment mainAxisAlignment; const LabeledCheckbox({ required this.label, @@ -15,6 +17,7 @@ class LabeledCheckbox extends StatelessWidget { this.initialValue = false, this.disabled = false, this.focused = false, + this.mainAxisAlignment = MainAxisAlignment.center, super.key, }); @@ -25,13 +28,11 @@ class LabeledCheckbox extends StatelessWidget { decoration: BoxDecoration( border: Border.all( color: focused ? context.appColors.controlColor : Colors.transparent, - width: 1, - strokeAlign: BorderSide.strokeAlignInside, ), borderRadius: BorderRadius.circular(5), ), child: Row( - mainAxisAlignment: MainAxisAlignment.center, + mainAxisAlignment: mainAxisAlignment, children: [ MSHCheckbox( value: initialValue, @@ -47,7 +48,7 @@ class LabeledCheckbox extends StatelessWidget { }, size: 20, ), - const SizedBox(width: 10), + const Gap(10), Text( label, style: context.appTextStyles.fs18, diff --git a/lib/presentation/widget/inputs/labeled_segmented_control.dart b/lib/presentation/widget/inputs/labeled_segmented_control.dart index 81e48b40..5e897081 100644 --- a/lib/presentation/widget/inputs/labeled_segmented_control.dart +++ b/lib/presentation/widget/inputs/labeled_segmented_control.dart @@ -21,7 +21,6 @@ class LabeledSegmentedControl extends StatelessWidget { return Padding( padding: const EdgeInsets.only(right: 10), child: Row( - mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( @@ -50,18 +49,20 @@ class LabeledSegmentedControl extends StatelessWidget { } Map _mapValues(BuildContext context) { - Map result = {}; - for (String value in values) { - result.addAll({ - value: Text( - value.titleCase, - style: context.appTextStyles.fs18?.copyWith( - color: selectedValue == value - ? context.appColors.textColor - : context.appColors.fadedColor, + final result = {}; + for (final value in values) { + result.addAll( + { + value: Text( + value.titleCase, + style: context.appTextStyles.fs18?.copyWith( + color: selectedValue == value + ? context.appColors.textColor + : context.appColors.fadedColor, + ), ), - ) - }); + }, + ); } return result; } diff --git a/lib/presentation/widget/inputs/switch_with_label.dart b/lib/presentation/widget/inputs/switch_with_label.dart index 009c594d..2407d25e 100644 --- a/lib/presentation/widget/inputs/switch_with_label.dart +++ b/lib/presentation/widget/inputs/switch_with_label.dart @@ -9,9 +9,9 @@ class SwitchWithLabel extends StatelessWidget { const SwitchWithLabel({ required this.label, - this.subLabel, required this.valueSetter, required this.initialValue, + this.subLabel, super.key, }); @@ -20,7 +20,6 @@ class SwitchWithLabel extends StatelessWidget { return Padding( padding: const EdgeInsets.only(right: 8), child: Row( - mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ SizedBox( @@ -39,7 +38,9 @@ class SwitchWithLabel extends StatelessWidget { subLabel ?? '', textAlign: TextAlign.left, style: context.appTextStyles.fs18?.copyWith( - color: context.appColors.textColor, fontSize: 13), + color: context.appColors.textColor, + fontSize: 13, + ), ), ], ), @@ -47,9 +48,7 @@ class SwitchWithLabel extends StatelessWidget { CupertinoSwitch( value: initialValue, activeColor: context.appColors.contrastColor, - onChanged: (value) { - valueSetter.call(value); - }, + onChanged: valueSetter.call, ), ], ), diff --git a/lib/presentation/widget/inputs/text_field_with_label.dart b/lib/presentation/widget/inputs/text_field_with_label.dart index b33bb27f..043a5bc3 100644 --- a/lib/presentation/widget/inputs/text_field_with_label.dart +++ b/lib/presentation/widget/inputs/text_field_with_label.dart @@ -53,7 +53,9 @@ class TextFieldWithLabel extends StatelessWidget { subLabel ?? '', textAlign: TextAlign.left, style: context.appTextStyles.fs18?.copyWith( - color: context.appColors.textColor, fontSize: 13), + color: context.appColors.textColor, + fontSize: 13, + ), ), ], ) @@ -72,7 +74,9 @@ class TextFieldWithLabel extends StatelessWidget { Text( subLabel ?? '', style: context.appTextStyles.fs18?.copyWith( - color: context.appColors.textColor, fontSize: 13), + color: context.appColors.textColor, + fontSize: 13, + ), ), ], ), diff --git a/lib/presentation/widget/title_bar.dart b/lib/presentation/widget/title_bar.dart index b0866f21..6939f960 100644 --- a/lib/presentation/widget/title_bar.dart +++ b/lib/presentation/widget/title_bar.dart @@ -1,11 +1,12 @@ import 'package:flutter/cupertino.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; +const double _titleBarHeight = 100; + class TitleBar extends StatelessWidget implements ObstructingPreferredSizeWidget { final String title; final List? actions; - final _titleBarHeight = 100.0; const TitleBar({ required this.title, @@ -20,25 +21,26 @@ class TitleBar extends StatelessWidget color: context.appColors.contrastColor, padding: const EdgeInsets.all(20), child: Align( - alignment: Alignment.bottomCenter, - child: Row( - children: [ - Text( - title, - style: context.appTextStyles.fs28?.copyWith( - color: context.appColors.textColor, - fontWeight: FontWeight.w100, - ), + alignment: Alignment.bottomCenter, + child: Row( + children: [ + Text( + title, + style: context.appTextStyles.fs28?.copyWith( + color: context.appColors.textColor, + fontWeight: FontWeight.w100, ), - const Spacer(), - ...actions ?? List.empty(), - ], - )), + ), + const Spacer(), + ...actions ?? List.empty(), + ], + ), + ), ); } @override - Size get preferredSize => Size.fromHeight(_titleBarHeight); + Size get preferredSize => const Size.fromHeight(_titleBarHeight); @override bool shouldFullyObstruct(BuildContext context) { diff --git a/lib/util/commands.dart b/lib/util/commands.dart index d3c5ebf2..f57b8baf 100644 --- a/lib/util/commands.dart +++ b/lib/util/commands.dart @@ -1,4 +1,4 @@ -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; class Commands { ///common commands @@ -6,7 +6,7 @@ class Commands { 'echo "Complete with exit code: 0"'; static String getOpenAndroidStudioCommand() => - 'open -a \'Android Studio.app\' .'; + "open -a 'Android Studio.app' ."; static String getGitBranchesCommand() => 'git ls-remote https://github.com/Onix-Systems/onix-flutter-project-generator.git'; @@ -34,7 +34,7 @@ class Commands { required String masonBrickBranch, }) { final branchFolder = masonBrickBranch.replaceAll('/', '-'); - return 'mason add -g flutter_clean_base --path \'$projectPath/bricks/onix-flutter-project-generator-$branchFolder/bricks/flutter_clean_base\''; + return "mason add -g flutter_clean_base --path '$projectPath/bricks/onix-flutter-project-generator-$branchFolder/bricks/flutter_clean_base'"; } static String getMasonMakeBrickCommand() => diff --git a/lib/util/extension/codelines_extension.dart b/lib/util/extension/codelines_extension.dart index fab78c4b..1184546f 100644 --- a/lib/util/extension/codelines_extension.dart +++ b/lib/util/extension/codelines_extension.dart @@ -1,3 +1,7 @@ -extension CodeLineExtension on List { +extension CodeLineExtensionList on List { + void addNewLine() => add(''); +} + +extension CodeLineExtensionSet on Set { void addNewLine() => add(''); } diff --git a/lib/util/extension/config_file_extension.dart b/lib/util/extension/config_file_extension.dart index 38e01001..dea51a7d 100644 --- a/lib/util/extension/config_file_extension.dart +++ b/lib/util/extension/config_file_extension.dart @@ -27,6 +27,8 @@ extension ConfigFileExtension on File { 'theme_generate': config.theming.name == 'themeTailor', 'branch': config.branch, 'screen_util': config.useScreenUtil, + 'state_management': config.stateManager.name, + 'sentry': config.sentry, }, ); return writeAsString(configContent); diff --git a/lib/util/extension/failure_dialog_extension.dart b/lib/util/extension/failure_dialog_extension.dart index 9670423c..9d6e9b5b 100644 --- a/lib/util/extension/failure_dialog_extension.dart +++ b/lib/util/extension/failure_dialog_extension.dart @@ -1,5 +1,5 @@ import 'package:flutter/cupertino.dart'; -import 'package:onix_flutter_bricks/core/app/localization/generated/l10n.dart'; +import 'package:onix_flutter_bricks/app/localization/generated/l10n.dart'; import 'package:onix_flutter_bricks/domain/entity/failure/signing_failure.dart'; import 'package:onix_flutter_bricks/presentation/style/theme/theme_extension/ext.dart'; import 'package:onix_flutter_bricks/presentation/widget/dialogs/dialog.dart'; diff --git a/lib/util/extension/project_config_extension.dart b/lib/util/extension/project_config_extension.dart index a490ee8e..45ca44bc 100644 --- a/lib/util/extension/project_config_extension.dart +++ b/lib/util/extension/project_config_extension.dart @@ -1,6 +1,6 @@ import 'dart:math'; -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; import 'package:onix_flutter_bricks/domain/entity/config/config.dart'; import 'package:onix_flutter_bricks/util/extension/flavor_extension.dart'; @@ -12,7 +12,7 @@ extension ProjectConfigExtension on Config { if (signingVars[6].isEmpty) { return List.generate(20, (index) { return AppConsts.signingKeyPassChars[ - (Random.secure().nextInt(AppConsts.signingKeyPassChars.length))]; + Random.secure().nextInt(AppConsts.signingKeyPassChars.length)]; }).join(); } else { return signingVars[6]; @@ -23,9 +23,9 @@ extension ProjectConfigExtension on Config { if (flavors.isEmpty) { return {}; } - var output = flavors.flavorStringToSet(); + final output = flavors.flavorStringToSet(); - for (var flavor in output) { + for (final flavor in output) { if (flavor.isEmpty || flavor == ' ') { output.remove(flavor); } diff --git a/lib/util/extension/swagger_extensions.dart b/lib/util/extension/swagger_extensions.dart index 397983ae..66e49534 100644 --- a/lib/util/extension/swagger_extensions.dart +++ b/lib/util/extension/swagger_extensions.dart @@ -9,6 +9,7 @@ extension SwaggerExtensions on String { final after = substring(startIndex + from.length); return '$before$to$after'; } + return this; } diff --git a/lib/util/extension/version_extension.dart b/lib/util/extension/version_extension.dart index fb92ad62..80eeb4da 100644 --- a/lib/util/extension/version_extension.dart +++ b/lib/util/extension/version_extension.dart @@ -1,7 +1,7 @@ extension VersionExtension on String { int asIntVersion() { - var versionClear = replaceAll('.', ''); - var versionMissedSymbols = 4 - versionClear.length; + final versionClear = replaceAll('.', ''); + final versionMissedSymbols = 4 - versionClear.length; var addition = ''; if (versionMissedSymbols > 0) { for (var i = 0; i < versionMissedSymbols; i++) { diff --git a/lib/util/flavors_util.dart b/lib/util/flavors_util.dart index ca5a2ac9..3f730d83 100644 --- a/lib/util/flavors_util.dart +++ b/lib/util/flavors_util.dart @@ -1,6 +1,6 @@ -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; -abstract final class FlavorsUtil { +class FlavorsUtil { static Set joinFlavors({ required bool flavorize, required String selectedFlavors, @@ -16,4 +16,6 @@ abstract final class FlavorsUtil { return flavors; } + + const FlavorsUtil._(); } diff --git a/lib/util/makefile/makefile_base.dart b/lib/util/makefile/makefile_base.dart index 2467f16e..ad2ceda0 100644 --- a/lib/util/makefile/makefile_base.dart +++ b/lib/util/makefile/makefile_base.dart @@ -13,7 +13,7 @@ abstract class MakefileBase { return [ '$name:${dependencies.isNotEmpty ? ' $dependencies' : ''}', ...commands.map((e) => '\t$e'), - '' + '', ]; } } diff --git a/lib/util/process_runner.dart b/lib/util/process_runner.dart index 53449ff3..9e7cea43 100644 --- a/lib/util/process_runner.dart +++ b/lib/util/process_runner.dart @@ -54,8 +54,8 @@ class ProcessRunner { }, ); - _process?.stdin.writeln('source \$HOME/.zshrc'); - _process?.stdin.writeln('source \$HOME/.bash_profile'); + _process?.stdin.writeln(r'source $HOME/.zshrc'); + _process?.stdin.writeln(r'source $HOME/.bash_profile'); } void execCommand(String command) { diff --git a/lib/util/project_name_validator.dart b/lib/util/project_name_validator.dart index 0ac85cd2..6ae6154b 100644 --- a/lib/util/project_name_validator.dart +++ b/lib/util/project_name_validator.dart @@ -1,4 +1,4 @@ -import 'package:onix_flutter_bricks/core/app/app_consts.dart'; +import 'package:onix_flutter_bricks/app/app_consts.dart'; abstract final class ProjectNameValidator { static bool isValidName(String value) { @@ -32,6 +32,6 @@ abstract final class ProjectNameValidator { 'test', 'utf', 'watcher', - 'yaml' + 'yaml', }; } diff --git a/lib/util/type_matcher.dart b/lib/util/type_matcher.dart index e427df4c..78b43cf2 100644 --- a/lib/util/type_matcher.dart +++ b/lib/util/type_matcher.dart @@ -68,7 +68,7 @@ class TypeMatcher { static String defaultTypeValue(String type) { switch (type) { case 'string': - return '\'\''; + return "''"; case 'integer': return '-1'; case 'number': diff --git a/macos/Podfile.lock b/macos/Podfile.lock index 2fd62324..3f1cbd6b 100644 --- a/macos/Podfile.lock +++ b/macos/Podfile.lock @@ -58,14 +58,14 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: connectivity_plus: ddd7f30999e1faaef5967c23d5b6d503d10434db - file_selector_macos: 54fdab7caa3ac3fc43c9fac4d7d8d231277f8cf2 + file_selector_macos: cc3858c981fe6889f364731200d6232dac1d812d flutter_secure_storage_macos: 59459653abe1adb92abbc8ea747d79f8d19866c9 FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24 - package_info_plus: 02d7a575e80f194102bef286361c6c326e4c29ce + package_info_plus: fa739dd842b393193c5ca93c26798dff6e3d0e0c path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46 screen_retriever: 59634572a57080243dd1bf715e55b6c54f241a38 shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78 - url_launcher_macos: 5f437abeda8c85500ceb03f5c1938a8c5a705399 + url_launcher_macos: c82c93949963e55b228a30115bd219499a6fe404 window_manager: 3a1844359a6295ab1e47659b1a777e36773cd6e8 PODFILE CHECKSUM: 33dc0a74a37eaaaa9a4d991374cc1fb2ce00b9ca diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift index d53ef643..8e02df28 100644 --- a/macos/Runner/AppDelegate.swift +++ b/macos/Runner/AppDelegate.swift @@ -1,7 +1,7 @@ import Cocoa import FlutterMacOS -@NSApplicationMain +@main class AppDelegate: FlutterAppDelegate { override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true diff --git a/pubspec.lock b/pubspec.lock index b2af7309..c91f3529 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -33,14 +33,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.5.0" - asn1lib: - dependency: transitive - description: - name: asn1lib - sha256: "58082b3f0dca697204dbab0ef9ff208bfaea7767ea771076af9a343488428dda" - url: "https://pub.dev" - source: hosted - version: "1.5.3" async: dependency: transitive description: @@ -178,21 +170,21 @@ packages: source: hosted version: "1.18.0" connectivity_plus: - dependency: "direct main" + dependency: transitive description: name: connectivity_plus - sha256: db7a4e143dc72cc3cb2044ef9b052a7ebfe729513e6a82943bc3526f784365b8 + sha256: "2056db5241f96cdc0126bd94459fc4cdc13876753768fc7a31c425e50a7177d0" url: "https://pub.dev" source: hosted - version: "6.0.3" + version: "6.0.5" connectivity_plus_platform_interface: dependency: transitive description: name: connectivity_plus_platform_interface - sha256: b6a56efe1e6675be240de39107281d4034b64ac23438026355b4234042a35adb + sha256: "42657c1715d48b167930d5f34d00222ac100475f73d10162ddf43e714932f204" url: "https://pub.dev" source: hosted - version: "2.0.0" + version: "2.0.1" convert: dependency: transitive description: @@ -205,10 +197,10 @@ packages: dependency: transitive description: name: cross_file - sha256: fedaadfa3a6996f75211d835aaeb8fede285dae94262485698afd832371b9a5e + sha256: "7caf6a750a0c04effbb52a676dce9a4a592e10ad35c34d6d2d0e4811160d5670" url: "https://pub.dev" source: hosted - version: "0.3.3+8" + version: "0.3.4+2" crypto: dependency: transitive description: @@ -242,29 +234,29 @@ packages: source: hosted version: "0.7.10" dio: - dependency: "direct main" + dependency: transitive description: name: dio - sha256: "11e40df547d418cc0c4900a9318b26304e665da6fa4755399a9ff9efd09034b5" + sha256: "5598aa796bbf4699afd5c67c0f5f6e2ed542afc956884b9cd58c306966efc260" url: "https://pub.dev" source: hosted - version: "5.4.3+1" + version: "5.7.0" dio_cache_interceptor: - dependency: "direct main" + dependency: transitive description: name: dio_cache_interceptor sha256: fb7905c0d12075d8786a6b63bffd64ae062d053f682cfaf28d145a2686507308 url: "https://pub.dev" source: hosted version: "3.5.0" - dio_cache_interceptor_hive_store: - dependency: "direct main" + dio_web_adapter: + dependency: transitive description: - name: dio_cache_interceptor_hive_store - sha256: "449b36541216cb20543228081125ad2995eb9712ec35bd030d85663ea1761895" + name: dio_web_adapter + sha256: "33259a9276d6cea88774a0000cfae0d861003497755969c92faa223108620dc8" url: "https://pub.dev" source: hosted - version: "3.2.2" + version: "2.0.0" dropdown_button2: dependency: "direct main" description: @@ -273,14 +265,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.9" - encrypt: - dependency: "direct main" - description: - name: encrypt - sha256: "62d9aa4670cc2a8798bab89b39fc71b6dfbacf615de6cf5001fb39f7e4a996a2" - url: "https://pub.dev" - source: hosted - version: "5.0.3" fake_async: dependency: transitive description: @@ -293,18 +277,18 @@ packages: dependency: transitive description: name: ffi - sha256: "493f37e7df1804778ff3a53bd691d8692ddf69702cf4c1c1096a2e41b4779e21" + sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6" url: "https://pub.dev" source: hosted - version: "2.1.2" + version: "2.1.3" file: dependency: transitive description: name: file - sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 url: "https://pub.dev" source: hosted - version: "7.0.0" + version: "7.0.1" file_selector: dependency: "direct main" description: @@ -325,26 +309,26 @@ packages: dependency: transitive description: name: file_selector_ios - sha256: "38ebf91ecbcfa89a9639a0854ccaed8ab370c75678938eebca7d34184296f0bb" + sha256: "94b98ad950b8d40d96fee8fa88640c2e4bd8afcdd4817993bd04e20310f45420" url: "https://pub.dev" source: hosted - version: "0.5.3" + version: "0.5.3+1" file_selector_linux: dependency: transitive description: name: file_selector_linux - sha256: "045d372bf19b02aeb69cacf8b4009555fb5f6f0b7ad8016e5f46dd1387ddd492" + sha256: "712ce7fab537ba532c8febdb1a8f167b32441e74acd68c3ccb2e36dcb52c4ab2" url: "https://pub.dev" source: hosted - version: "0.9.2+1" + version: "0.9.3" file_selector_macos: dependency: transitive description: name: file_selector_macos - sha256: f42eacb83b318e183b1ae24eead1373ab1334084404c8c16e0354f9a3e55d385 + sha256: "271ab9986df0c135d45c3cdb6bd0faa5db6f4976d3e4b437cf7d0f258d941bfc" url: "https://pub.dev" source: hosted - version: "0.9.4" + version: "0.9.4+2" file_selector_platform_interface: dependency: transitive description: @@ -357,18 +341,18 @@ packages: dependency: transitive description: name: file_selector_web - sha256: c0f025d460de3301b7bbbf837fc8d0759df85f182c635f1dd94934b4cdc92352 + sha256: c4c0ea4224d97a60a7067eca0c8fd419e708ff830e0c83b11a48faf566cec3e7 url: "https://pub.dev" source: hosted - version: "0.9.3" + version: "0.9.4+2" file_selector_windows: dependency: transitive description: name: file_selector_windows - sha256: d3547240c20cabf205c7c7f01a50ecdbc413755814d6677f3cb366f04abcead0 + sha256: "8f5d2f6590d51ecd9179ba39c64f722edc15226cc93dcc8698466ad36a4a85a4" url: "https://pub.dev" source: hosted - version: "0.9.3+1" + version: "0.9.3+3" fixnum: dependency: transitive description: @@ -386,10 +370,10 @@ packages: dependency: "direct main" description: name: flutter_bloc - sha256: f0ecf6e6eb955193ca60af2d5ca39565a86b8a142452c5b24d96fb477428f4d2 + sha256: b594505eac31a0518bdcb4b5b79573b8d9117b193cc80cc12e17d639b10aa27a url: "https://pub.dev" source: hosted - version: "8.1.5" + version: "8.1.6" flutter_lints: dependency: "direct dev" description: @@ -404,7 +388,7 @@ packages: source: sdk version: "0.0.0" flutter_secure_storage: - dependency: "direct main" + dependency: transitive description: name: flutter_secure_storage sha256: "165164745e6afb5c0e3e3fcc72a012fb9e58496fb26ffb92cf22e16a821e85d0" @@ -481,10 +465,10 @@ packages: dependency: "direct main" description: name: fluttertoast - sha256: "81b68579e23fcbcada2db3d50302813d2371664afe6165bc78148050ab94bf66" + sha256: "95f349437aeebe524ef7d6c9bde3e6b4772717cf46a0eb6a3ceaddc740b297cc" url: "https://pub.dev" source: hosted - version: "8.2.5" + version: "8.2.8" freezed: dependency: "direct dev" description: @@ -497,10 +481,10 @@ packages: dependency: "direct main" description: name: freezed_annotation - sha256: c3fd9336eb55a38cc1bbd79ab17573113a8deccd0ecbbf926cca3c62803b5c2d + sha256: c2e2d632dd9b8a2b7751117abcfc2b4888ecfe181bd9fca7170d9ef02e595fe2 url: "https://pub.dev" source: hosted - version: "2.4.1" + version: "2.4.4" frontend_server_client: dependency: transitive description: @@ -509,6 +493,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.0" + gap: + dependency: "direct main" + description: + name: gap + sha256: f19387d4e32f849394758b91377f9153a1b41d79513ef7668c088c77dbc6955d + url: "https://pub.dev" + source: hosted + version: "3.0.1" get_it: dependency: "direct main" description: @@ -549,30 +541,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.1" - hive: - dependency: "direct main" - description: - name: hive - sha256: "8dcf6db979d7933da8217edcec84e9df1bdb4e4edc7fc77dbd5aa74356d6d941" - url: "https://pub.dev" - source: hosted - version: "2.2.3" - hive_flutter: - dependency: "direct main" - description: - name: hive_flutter - sha256: dca1da446b1d808a51689fb5d0c6c9510c0a2ba01e22805d492c73b68e33eecc - url: "https://pub.dev" - source: hosted - version: "1.1.0" http: dependency: "direct main" description: name: http - sha256: a2bbf9d017fcced29139daa8ed2bba4ece450ab222871df93ca9eec6f80c34ba + sha256: b9c29a161230ee03d3ccf545097fccd9b87a5264228c5d348202e0f0c28f9010 url: "https://pub.dev" source: hosted - version: "1.2.0" + version: "1.2.2" http_multi_server: dependency: transitive description: @@ -589,14 +565,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.2" - internet_connection_checker: - dependency: "direct main" + internet_connection_checker_plus: + dependency: transitive description: - name: internet_connection_checker - sha256: "1c683e63e89c9ac66a40748b1b20889fd9804980da732bf2b58d6d5456c8e876" + name: internet_connection_checker_plus + sha256: "95da3194bdb98cb606b921f0e0007cbe55c32d6a7fa92d5debe59ef4183ce2a6" url: "https://pub.dev" source: hosted - version: "1.0.0+1" + version: "2.5.2" intl: dependency: "direct main" description: @@ -681,18 +657,18 @@ packages: dependency: "direct main" description: name: loader_overlay - sha256: "02deeeed0d4eaaeeada6ce7bb13426d7548acad1f71e4884ec4a010e0e4824d6" + sha256: b87bd0c5f4a0c8249613b1c1666344469177535a6b7782b620a4ff1b8f52efa1 url: "https://pub.dev" source: hosted - version: "4.0.0" + version: "4.0.2+1" logger: dependency: "direct main" description: name: logger - sha256: af05cc8714f356fd1f3888fb6741cbe9fbe25cdb6eedbab80e1a6db21047d4a4 + sha256: "697d067c60c20999686a0add96cf6aba723b3aa1f83ecf806a8097231529ec32" url: "https://pub.dev" source: hosted - version: "2.3.0" + version: "2.4.0" logging: dependency: transitive description: @@ -729,10 +705,10 @@ packages: dependency: transitive description: name: mime - sha256: "2e123074287cc9fd6c09de8336dae606d1ddb88d9ac47358826db698c176a1f2" + sha256: "801fd0b26f14a4a58ccb09d5892c3fbdeff209594300a542492cf13fba9d247a" url: "https://pub.dev" source: hosted - version: "1.0.5" + version: "1.0.6" msh_checkbox: dependency: "direct main" description: @@ -757,6 +733,30 @@ packages: url: "https://pub.dev" source: hosted version: "0.5.0" + onix_flutter_bloc: + dependency: "direct main" + description: + name: onix_flutter_bloc + sha256: c466bb93996e89de394f4cf8750f73cf88d9715cb6e61e5d9e0ec6a0f91a28c9 + url: "https://pub.dev" + source: hosted + version: "0.0.3" + onix_flutter_core: + dependency: "direct main" + description: + name: onix_flutter_core + sha256: "74d8a2692bb566072302ac227decf89297930d62cc64a5804dff009b6bb58063" + url: "https://pub.dev" + source: hosted + version: "0.0.5" + onix_flutter_core_models: + dependency: "direct main" + description: + name: onix_flutter_core_models + sha256: "6e247447fb877221d4a8c3512da491db9da86af746cf6cfa91c9d9eaa79b7588" + url: "https://pub.dev" + source: hosted + version: "0.0.2" package_config: dependency: transitive description: @@ -769,18 +769,18 @@ packages: dependency: "direct main" description: name: package_info_plus - sha256: "88bc797f44a94814f2213db1c9bd5badebafdfb8290ca9f78d4b9ee2a3db4d79" + sha256: a75164ade98cb7d24cfd0a13c6408927c6b217fa60dee5a7ff5c116a58f28918 url: "https://pub.dev" source: hosted - version: "5.0.1" + version: "8.0.2" package_info_plus_platform_interface: dependency: transitive description: name: package_info_plus_platform_interface - sha256: "9bc8ba46813a4cc42c66ab781470711781940780fd8beddd0c3da62506d3a6c6" + sha256: ac1f4a4847f1ade8e6a87d1f39f5d7c67490738642e2542f559ec38c37489a66 url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "3.0.1" path: dependency: transitive description: @@ -801,10 +801,10 @@ packages: dependency: transitive description: name: path_provider - sha256: c9e7d3a4cd1410877472158bee69963a4579f78b68c65a2b7d40d1a7a88bb161 + sha256: fec0d61223fba3154d87759e3cc27fe2c8dc498f6386c6d6fc80d1afdd1bf378 url: "https://pub.dev" source: hosted - version: "2.1.3" + version: "2.1.4" path_provider_android: dependency: transitive description: @@ -841,10 +841,10 @@ packages: dependency: transitive description: name: path_provider_windows - sha256: "8bc9f22eee8690981c22aa7fc602f5c85b497a6fb2ceb35ee5a5e5ed85ad8170" + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 url: "https://pub.dev" source: hosted - version: "2.2.1" + version: "2.3.0" petitparser: dependency: transitive description: @@ -857,10 +857,10 @@ packages: dependency: transitive description: name: platform - sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec" + sha256: "9b71283fc13df574056616011fb138fd3b793ea47cc509c189a6c3fa5f8a1a65" url: "https://pub.dev" source: hosted - version: "3.1.4" + version: "3.1.5" plugin_platform_interface: dependency: transitive description: @@ -869,14 +869,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.8" - pointycastle: - dependency: transitive - description: - name: pointycastle - sha256: "4be0097fcf3fd3e8449e53730c631200ebc7b88016acecab2b0da2f0149222fe" - url: "https://pub.dev" - source: hosted - version: "3.9.1" pool: dependency: transitive description: @@ -886,13 +878,13 @@ packages: source: hosted version: "1.5.1" pretty_dio_logger: - dependency: "direct main" + dependency: transitive description: name: pretty_dio_logger - sha256: "00b80053063935cf9a6190da344c5373b9d0e92da4c944c878ff2fbef0ef6dc2" + sha256: "36f2101299786d567869493e2f5731de61ce130faa14679473b26905a92b6407" url: "https://pub.dev" source: hosted - version: "1.3.1" + version: "1.4.0" process_run: dependency: "direct main" description: @@ -934,7 +926,7 @@ packages: source: hosted version: "4.1.0" retry: - dependency: "direct main" + dependency: transitive description: name: retry sha256: "822e118d5b3aafed083109c72d5f484c6dc66707885e07c0fbcb8b986bba7efc" @@ -958,7 +950,7 @@ packages: source: hosted version: "0.9.9" shared_preferences: - dependency: "direct main" + dependency: transitive description: name: shared_preferences sha256: d3bbe5553a986e83980916ded2f0b435ef2e1893dfaa29d5a7a790d0eca12180 @@ -977,42 +969,42 @@ packages: dependency: transitive description: name: shared_preferences_foundation - sha256: "0a8a893bf4fd1152f93fec03a415d11c27c74454d96e2318a7ac38dd18683ab7" + sha256: "07e050c7cd39bad516f8d64c455f04508d09df104be326d8c02551590a0d513d" url: "https://pub.dev" source: hosted - version: "2.4.0" + version: "2.5.3" shared_preferences_linux: dependency: transitive description: name: shared_preferences_linux - sha256: "9f2cbcf46d4270ea8be39fa156d86379077c8a5228d9dfdb1164ae0bb93f1faa" + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" url: "https://pub.dev" source: hosted - version: "2.3.2" + version: "2.4.1" shared_preferences_platform_interface: dependency: transitive description: name: shared_preferences_platform_interface - sha256: "22e2ecac9419b4246d7c22bfbbda589e3acf5c0351137d87dd2939d984d37c3b" + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" url: "https://pub.dev" source: hosted - version: "2.3.2" + version: "2.4.1" shared_preferences_web: dependency: transitive description: name: shared_preferences_web - sha256: "7b15ffb9387ea3e237bb7a66b8a23d2147663d391cafc5c8f37b2e7b4bde5d21" + sha256: "59dc807b94d29d52ddbb1b3c0d3b9d0a67fc535a64e62a5542c8db0513fcb6c2" url: "https://pub.dev" source: hosted - version: "2.2.2" + version: "2.4.1" shared_preferences_windows: dependency: transitive description: name: shared_preferences_windows - sha256: "841ad54f3c8381c480d0c9b508b89a34036f512482c407e6df7a9c4aa2ef8f59" + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" url: "https://pub.dev" source: hosted - version: "2.3.2" + version: "2.4.1" shelf: dependency: transitive description: @@ -1142,10 +1134,10 @@ packages: dependency: "direct main" description: name: url_launcher - sha256: "21b704ce5fa560ea9f3b525b43601c678728ba46725bab9b01187b4831377ed3" + sha256: "9d06212b1362abc2f0f0d78e6f09f726608c74e3b9462e8368bb03314aa8d603" url: "https://pub.dev" source: hosted - version: "6.3.0" + version: "6.3.1" url_launcher_android: dependency: transitive description: @@ -1158,26 +1150,26 @@ packages: dependency: transitive description: name: url_launcher_ios - sha256: "7068716403343f6ba4969b4173cbf3b84fc768042124bc2c011e5d782b24fe89" + sha256: e43b677296fadce447e987a2f519dcf5f6d1e527dc35d01ffab4fff5b8a7063e url: "https://pub.dev" source: hosted - version: "6.3.0" + version: "6.3.1" url_launcher_linux: dependency: transitive description: name: url_launcher_linux - sha256: ab360eb661f8879369acac07b6bb3ff09d9471155357da8443fd5d3cf7363811 + sha256: e2b9622b4007f97f504cd64c0128309dfb978ae66adbe944125ed9e1750f06af url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "3.2.0" url_launcher_macos: dependency: transitive description: name: url_launcher_macos - sha256: "9a1a42d5d2d95400c795b2914c36fdcb525870c752569438e4ebb09a2b5d90de" + sha256: "769549c999acdb42b8bcfa7c43d72bf79a382ca7441ab18a808e101149daf672" url: "https://pub.dev" source: hosted - version: "3.2.0" + version: "3.2.1" url_launcher_platform_interface: dependency: transitive description: @@ -1190,26 +1182,26 @@ packages: dependency: transitive description: name: url_launcher_web - sha256: fff0932192afeedf63cdd50ecbb1bc825d31aed259f02bb8dba0f3b729a5e88b + sha256: "772638d3b34c779ede05ba3d38af34657a05ac55b06279ea6edd409e323dca8e" url: "https://pub.dev" source: hosted - version: "2.2.3" + version: "2.3.3" url_launcher_windows: dependency: transitive description: name: url_launcher_windows - sha256: ecf9725510600aa2bb6d7ddabe16357691b6d2805f66216a97d1b881e21beff7 + sha256: "49c10f879746271804767cb45551ec5592cdab00ee105c06dddde1a98f73b185" url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "3.1.2" uuid: dependency: transitive description: name: uuid - sha256: "814e9e88f21a176ae1359149021870e87f7cddaf633ab678a5d2b0bff7fd1ba8" + sha256: a5be9ef6618a7ac1e964353ef476418026db906c4facdedaa299b7a2e71690ff url: "https://pub.dev" source: hosted - version: "4.4.0" + version: "4.5.1" vector_graphics: dependency: transitive description: @@ -1262,18 +1254,18 @@ packages: dependency: transitive description: name: web - sha256: "4188706108906f002b3a293509234588823c8c979dc83304e229ff400c996b05" + sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27" url: "https://pub.dev" source: hosted - version: "0.4.2" + version: "0.5.1" web_socket_channel: dependency: transitive description: name: web_socket_channel - sha256: "939ab60734a4f8fa95feacb55804fa278de28bdeef38e616dc08e44a84adea23" + sha256: "58c6666b342a38816b2e7e50ed0f1e261959630becd4c879c4f26bfa14aa5a42" url: "https://pub.dev" source: hosted - version: "2.4.3" + version: "2.4.5" win32: dependency: transitive description: @@ -1294,10 +1286,10 @@ packages: dependency: transitive description: name: xdg_directories - sha256: faea9dee56b520b55a566385b84f2e8de55e7496104adada9962e0bd11bcff1d + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" url: "https://pub.dev" source: hosted - version: "1.0.4" + version: "1.1.0" xml: dependency: transitive description: @@ -1307,7 +1299,7 @@ packages: source: hosted version: "6.5.0" yaml: - dependency: "direct main" + dependency: transitive description: name: yaml sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" diff --git a/pubspec.yaml b/pubspec.yaml index 3da79184..6b421b69 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: Onix Flutter Clean Architecture publish_to: 'none' # Remove this line if you wish to publish to pub.dev -version: 1.2.0+29 +version: 1.3.0+30 environment: sdk: '>=3.2.0 <4.0.0' @@ -27,24 +27,10 @@ dependencies: freezed_annotation: ^2.4.1 flutter_bloc: ^8.1.3 json_annotation: ^4.8.1 - http: ^1.2.0 collection: ^1.18.0 - package_info_plus: ^5.0.1 - yaml: ^3.1.2 + package_info_plus: ^8.0.2 url_launcher: ^6.2.4 - encrypt: ^5.0.3 - hive: ^2.2.3 - flutter_secure_storage: ^9.0.0 loader_overlay: ^4.0.0 - dio: ^5.4.0 - retry: ^3.1.2 - connectivity_plus: ^6.0.3 - internet_connection_checker: ^1.0.0+1 - shared_preferences: ^2.2.2 - dio_cache_interceptor: ^3.5.0 - dio_cache_interceptor_hive_store: ^3.2.2 - hive_flutter: ^1.1.0 - pretty_dio_logger: ^1.3.1 fluttertoast: ^8.2.4 go_router: ^13.1.0 intl: ^0.18.1 @@ -53,6 +39,11 @@ dependencies: searchfield: ^0.9.0 google_fonts: ^6.1.0 flutter_styled_toast: ^2.2.1 + gap: ^3.0.1 + onix_flutter_bloc: ^0.0.3 + onix_flutter_core_models: ^0.0.2 + onix_flutter_core: ^0.0.5 + http: ^1.2.2 dev_dependencies: flutter_test: @@ -80,7 +71,7 @@ flutter: flutter_intl: enabled: true - arb_dir: lib/core/app/localization/l10n - output_dir: lib/core/app/localization/generated + arb_dir: lib/app/localization/l10n + output_dir: lib/app/localization/generated #generated with mason