From 0e73b586ecd9351d7793a42522f7ebcad0d30463 Mon Sep 17 00:00:00 2001 From: oussama berhili Date: Wed, 8 Jan 2025 09:29:33 +0100 Subject: [PATCH 1/2] Bump sqlite3_flutter_libs from 0.5.27 to 0.5.28 Bumps [sqlite3_flutter_libs](https://github.com/simolus3/sqlite3.dart) from 0.5.27 to 0.5.28. - [Release notes](https://github.com/simolus3/sqlite3.dart/releases) - [Commits](https://github.com/simolus3/sqlite3.dart/compare/sqlite3_flutter_libs-0.5.27...sqlite3_flutter_libs-0.5.28) --- updated-dependencies: - dependency-name: sqlite3_flutter_libs dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] ## Description (Proposed Changes) (Please try to mention in bullet points.) - - ## Link to the issue : (Add link of the issue you have proposed changes to) - Link : ## Tests Please make sure to add tests when implementing new features. ## Checklist Please check that the PR fulfills all requirements listed below by checking the relevant checkboxes (`[x]`). This will ensure a smooth and quick review process. - [ ] Set a 100 character limit in your editor/IDE to avoid white space diffs in the PR - [ ] Tests for the changes have been added (for bug fixes / features) - [ ] Added yourself to AUTHORS.md - [ ] Updated/added relevant documentation (doc comments with `///`). - [ ] Added relevant reviewers. --- .gitignore | 6 + analysis_options.yaml | 200 +---- flatpak/scripts/flatpak_packager.dart | 52 +- flatpak/scripts/flatpak_shared.dart | 65 +- flatpak/scripts/manifest_generator.dart | 21 +- ...1_dashboard.dart => dashboard_widget.dart} | 12 +- .../{3_gym_mode.dart => gym_mode_widget.dart} | 6 +- integration_test/make_screenshots_test.dart | 39 +- ...urements.dart => measurements_widget.dart} | 3 +- ...plan.dart => nutritional_plan_widget.dart} | 0 .../{6_weight.dart => weight_widget.dart} | 0 .../{2_workout.dart => workout_widget.dart} | 3 +- lib/database/exercises/type_converters.dart | 38 +- lib/exceptions/http_exception.dart | 8 +- lib/helpers/charts.dart | 4 +- lib/helpers/exercises/forms.dart | 6 +- lib/helpers/json.dart | 3 +- lib/helpers/misc.dart | 4 +- lib/helpers/platform.dart | 3 +- lib/helpers/ui.dart | 6 +- lib/main.dart | 33 +- lib/models/body_weight/weight_entry.dart | 3 +- lib/models/exercises/category.dart | 3 +- lib/models/exercises/comment.dart | 3 +- lib/models/exercises/equipment.dart | 3 +- lib/models/exercises/exercise.dart | 17 +- lib/models/exercises/exercise_api.dart | 6 +- lib/models/exercises/image.dart | 3 +- lib/models/exercises/language.dart | 3 +- lib/models/exercises/muscle.dart | 3 +- lib/models/exercises/translation.dart | 89 +- lib/models/exercises/translation.g.dart | 18 +- lib/models/exercises/variation.dart | 3 +- .../measurements/measurement_entry.dart | 10 +- lib/models/nutrition/ingredient.dart | 15 +- lib/models/nutrition/ingredient_image.dart | 3 +- lib/models/nutrition/log.dart | 8 +- lib/models/nutrition/meal.dart | 8 +- lib/models/nutrition/meal_item.dart | 3 +- lib/models/nutrition/nutritional_goals.dart | 29 +- lib/models/nutrition/nutritional_plan.dart | 21 +- lib/models/nutrition/weight_unit.dart | 3 +- lib/models/user/profile.dart | 3 +- lib/models/workouts/day.dart | 3 +- lib/models/workouts/log.dart | 7 +- lib/models/workouts/repetition_unit.dart | 3 +- lib/models/workouts/session.dart | 15 +- lib/models/workouts/set.dart | 4 +- lib/models/workouts/setting.dart | 16 +- lib/models/workouts/weight_unit.dart | 3 +- lib/models/workouts/workout_plan.dart | 10 +- lib/providers/add_exercise.dart | 39 +- lib/providers/auth.dart | 2 +- lib/providers/base_provider.dart | 3 +- lib/providers/body_weight.dart | 6 +- lib/providers/exercises.dart | 75 +- lib/providers/gallery.dart | 14 +- lib/providers/measurement.dart | 28 +- lib/providers/nutrition.dart | 27 +- lib/providers/user.dart | 7 +- lib/providers/workout_plans.dart | 47 +- lib/screens/add_exercise_screen.dart | 31 +- lib/screens/auth_screen.dart | 42 +- lib/screens/exercise_screen.dart | 4 +- lib/screens/exercises_screen.dart | 3 +- lib/screens/form_screen.dart | 3 +- lib/screens/home_tabs_screen.dart | 3 +- lib/screens/log_meal_screen.dart | 49 +- lib/screens/log_meals_screen.dart | 3 +- lib/screens/measurement_entries_screen.dart | 12 +- lib/screens/nutritional_diary_screen.dart | 6 +- lib/screens/nutritional_plan_screen.dart | 16 +- lib/screens/nutritional_plans_screen.dart | 7 +- lib/screens/weight_screen.dart | 3 +- lib/screens/workout_plan_screen.dart | 11 +- lib/screens/workout_plans_screen.dart | 3 +- lib/theme/theme.dart | 1 - .../add_exercise_dropdown_button.dart | 6 +- .../add_exercise_multiselect_button.dart | 11 +- .../add_exercise/add_exercise_text_area.dart | 6 +- .../mixins/image_picker_mixin.dart | 13 +- lib/widgets/add_exercise/preview_images.dart | 11 +- .../add_exercise/steps/step1basics.dart | 20 +- .../add_exercise/steps/step2variations.dart | 19 +- .../add_exercise/steps/step3description.dart | 3 +- .../add_exercise/steps/step4translations.dart | 10 +- .../add_exercise/steps/step5images.dart | 6 +- lib/widgets/core/about.dart | 8 +- lib/widgets/core/app_bar.dart | 9 +- lib/widgets/core/core.dart | 5 +- lib/widgets/core/settings.dart | 18 +- lib/widgets/dashboard/calendar.dart | 19 +- lib/widgets/dashboard/widgets.dart | 61 +- lib/widgets/exercises/exercises.dart | 79 +- lib/widgets/exercises/filter_modal.dart | 17 +- lib/widgets/exercises/filter_row.dart | 9 +- lib/widgets/exercises/forms.dart | 53 +- lib/widgets/exercises/list_tile.dart | 7 +- lib/widgets/exercises/videos.dart | 3 +- lib/widgets/gallery/forms.dart | 3 +- lib/widgets/gallery/overview.dart | 12 +- lib/widgets/measurements/categories.dart | 3 +- lib/widgets/measurements/categories_card.dart | 4 +- lib/widgets/measurements/charts.dart | 36 +- lib/widgets/measurements/entries.dart | 14 +- lib/widgets/measurements/forms.dart | 24 +- lib/widgets/measurements/helpers.dart | 25 +- lib/widgets/nutrition/charts.dart | 38 +- lib/widgets/nutrition/forms.dart | 360 ++++---- lib/widgets/nutrition/helpers.dart | 32 +- lib/widgets/nutrition/ingredient_dialogs.dart | 22 +- .../nutrition/macro_nutrients_table.dart | 27 +- lib/widgets/nutrition/meal.dart | 38 +- lib/widgets/nutrition/nutrition_tiles.dart | 7 +- .../nutrition/nutritional_diary_detail.dart | 30 +- .../nutrition/nutritional_diary_table.dart | 11 +- .../nutrition/nutritional_plan_detail.dart | 11 +- .../nutrition/nutritional_plans_list.dart | 18 +- lib/widgets/nutrition/widgets.dart | 37 +- lib/widgets/user/forms.dart | 15 +- lib/widgets/weight/forms.dart | 21 +- lib/widgets/weight/weight_overview.dart | 13 +- lib/widgets/workouts/app_bar.dart | 3 +- lib/widgets/workouts/charts.dart | 19 +- lib/widgets/workouts/day.dart | 17 +- lib/widgets/workouts/forms.dart | 187 ++-- lib/widgets/workouts/gym_mode.dart | 104 ++- lib/widgets/workouts/log.dart | 19 +- lib/widgets/workouts/workout_plan_detail.dart | 3 +- lib/widgets/workouts/workout_plans_list.dart | 18 +- pubspec.lock | 148 ++-- pubspec.yaml | 4 +- test/auth/auth_provider_test.dart | 26 +- test/auth/auth_screen_test.dart | 50 +- test/auth/auth_screen_test.mocks.dart | 222 ++--- test/core/settings_test.dart | 12 +- test/core/settings_test.mocks.dart | 619 ++++--------- test/exercises/contribute_exercise_test.dart | 15 +- .../contribute_exercise_test.mocks.dart | 311 ++----- test/exercises/exercise_provider_db_test.dart | 147 ++-- .../exercise_provider_load_test.dart | 17 +- test/exercises/exercise_provider_test.dart | 82 +- .../exercises_detail_widget_test.dart | 18 +- test/exercises/model_exercise_test.dart | 11 +- test/gallery/gallery_form_test.dart | 12 +- test/gallery/gallery_form_test.mocks.dart | 219 ++--- test/gallery/gallery_provider_test.dart | 3 +- test/gallery/gallery_screen_test.dart | 18 +- test/gallery/gallery_screen_test.mocks.dart | 219 ++--- .../measurement_categories_screen_test.dart | 31 +- ...surement_categories_screen_test.mocks.dart | 139 +-- .../measurement_category_test.dart | 9 +- .../measurement_entries_screen_test.dart | 23 +- .../measurement_provider_test.dart | 85 +- .../measurement_provider_test.mocks.dart | 146 +--- test/nutrition/nutrition_provider_test.dart | 18 +- test/nutrition/nutritional_diary_test.dart | 15 +- .../nutrition/nutritional_meal_form_test.dart | 6 +- .../nutritional_meal_form_test.mocks.dart | 333 ++----- .../nutritional_meal_item_form_test.dart | 114 ++- .../nutrition/nutritional_plan_form_test.dart | 26 +- .../nutritional_plan_form_test.mocks.dart | 333 ++----- .../nutritional_plan_model_test.dart | 12 +- .../nutritional_plan_screen_test.dart | 18 +- .../nutritional_plan_screen_test.mocks.dart | 540 ++++-------- .../nutritional_plans_screen_test.dart | 15 +- .../nutritional_plans_screen_test.mocks.dart | 540 ++++-------- .../nutritional_values_class_test.dart | 15 +- test/other/base_provider_test.dart | 33 +- test/other/base_provider_test.mocks.dart | 222 ++--- test/user/provider_test.mocks.dart | 146 +--- test/utils.dart | 5 +- test/weight/weight_form_test.dart | 12 +- test/weight/weight_model_test.dart | 15 +- test/weight/weight_provider_test.dart | 21 +- test/weight/weight_provider_test.mocks.dart | 146 +--- test/weight/weight_screen_test.mocks.dart | 478 +++-------- test/workout/gym_mode_screen_test.dart | 9 +- test/workout/gym_mode_screen_test.mocks.dart | 435 +++------- test/workout/plate_calculator_test.dart | 6 +- .../repetition_unit_form_widget_test.dart | 6 +- ...epetition_unit_form_widget_test.mocks.dart | 388 +++------ .../workout/weight_unit_form_widget_test.dart | 3 +- .../weight_unit_form_widget_test.mocks.dart | 105 +-- test/workout/workout_day_form_test.dart | 15 +- test/workout/workout_day_form_test.mocks.dart | 388 +++------ test/workout/workout_form_test.dart | 42 +- test/workout/workout_form_test.mocks.dart | 388 +++------ test/workout/workout_plan_model_test.dart | 6 +- test/workout/workout_plan_screen_test.dart | 12 +- .../workout_plan_screen_test.mocks.dart | 146 +--- test/workout/workout_plans_screen_test.dart | 27 +- .../workout_plans_screen_test.mocks.dart | 146 +--- test/workout/workout_provider_test.dart | 33 +- test/workout/workout_provider_test.mocks.dart | 146 +--- test/workout/workout_set_form_test.dart | 15 +- test/workout/workout_set_form_test.mocks.dart | 811 +++++------------- test_data/body_weight.dart | 6 +- test_data/exercises.dart | 126 +-- test_data/measurements.dart | 21 +- test_data/nutritional_plans.dart | 9 +- test_data/screenshots_exercises.dart | 626 +++++++------- test_data/workouts.dart | 3 +- test_driver/screenshot_driver.dart | 8 +- 204 files changed, 4888 insertions(+), 7526 deletions(-) rename integration_test/{1_dashboard.dart => dashboard_widget.dart} (88%) rename integration_test/{3_gym_mode.dart => gym_mode_widget.dart} (91%) rename integration_test/{4_measurements.dart => measurements_widget.dart} (92%) rename integration_test/{5_nutritional_plan.dart => nutritional_plan_widget.dart} (100%) rename integration_test/{6_weight.dart => weight_widget.dart} (100%) rename integration_test/{2_workout.dart => workout_widget.dart} (93%) diff --git a/.gitignore b/.gitignore index 0df000b82..dfd7a1724 100644 --- a/.gitignore +++ b/.gitignore @@ -53,3 +53,9 @@ app.*.map.json # Others /vendor/bundle/ruby/ /coverage/ + +# Generated files +*.g.dart +*.freezed.dart +*.gr.dart +*.gen.dart diff --git a/analysis_options.yaml b/analysis_options.yaml index 15127111c..47cf66e55 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,172 +1,38 @@ -include: package:flutter_lints/flutter.yaml +include: package:lint/analysis_options.yaml analyzer: - strong-mode: - implicit-casts: true # to be changed - implicit-dynamic: true # to be changed errors: - # Treat missing required parameters as a warning (not a hint) - missing_required_param: warning - # Treat missing returns as a warning (not a hint) - missing_return: warning - # Allow having TODOs in the code - todo: ignore - # Allow self-reference to deprecated members (we do this because otherwise we have - # to annotate every member in every test, assert, etc, when we deprecate something) - deprecated_member_use_from_same_package: ignore - # Ignore analyzer hints for updating pubspecs when using Future or - # Stream and not importing dart:async - # Please see https://github.com/flutter/flutter/pull/24528 for details. - sdk_version_async_exported_from_core: ignore + missing_return: error + must_be_immutable: error + must_call_super: error + invalid_use_of_protected_member: error + parameter_assignments: error + sort_unnamed_constructors_first: error + sort_pub_dependencies: ignore + always_use_package_imports: error + invalid_annotation_target: ignore + type_annotate_public_apis: false + use_build_context_synchronously: warning -linter: - rules: - # These rules are documented on and in the same order as - # the Dart Lint rules page to make maintenance easier - # https://github.com/dart-lang/linter/blob/master/example/all.yaml - always_declare_return_types: true - always_put_control_body_on_new_line: true - always_require_non_null_named_parameters: true - always_specify_types: false # decided against using it for now - annotate_overrides: true - avoid_bool_literals_in_conditional_expressions: true - avoid_classes_with_only_static_members: true - avoid_dynamic_calls: false # to be changed - avoid_empty_else: 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_init_to_null: true - avoid_null_checks_in_equality_operators: true - avoid_relative_lib_imports: true - avoid_renaming_method_parameters: true - avoid_return_types_on_setters: true - avoid_returning_null_for_void: true - avoid_shadowing_type_parameters: true - avoid_single_cascade_in_expression_statements: true - avoid_slow_async_io: true - avoid_type_to_string: true - avoid_types_as_parameter_names: true - avoid_unnecessary_containers: true - avoid_unused_constructor_parameters: true - avoid_void_async: false - await_only_futures: true - camel_case_extensions: true - camel_case_types: false - cancel_subscriptions: true - cast_nullable_to_non_nullable: false # to be changed - constant_identifier_names: false - control_flow_in_finally: true - deprecated_consistency: true - directives_ordering: true - empty_catches: false - empty_constructor_bodies: true - empty_statements: true - exhaustive_cases: true - file_names: true - flutter_style_todos: false - hash_and_equals: true - implementation_imports: true - iterable_contains_unrelated_type: true - leading_newlines_in_multiline_strings: true - library_names: true - library_prefixes: true - library_private_types_in_public_api: false - list_remove_unrelated_type: true - missing_whitespace_between_adjacent_strings: false - no_adjacent_strings_in_list: true - no_duplicate_case_values: true - no_logic_in_create_state: true - non_constant_identifier_names: true - noop_primitive_operations: true - null_check_on_nullable_type_parameter: true - null_closures: true - overridden_fields: true - package_api_docs: true - package_names: true - package_prefixed_library_names: true - prefer_adjacent_string_concatenation: true - prefer_asserts_in_initializer_lists: true - prefer_collection_literals: true - prefer_conditional_assignment: true - prefer_const_constructors: true - prefer_const_constructors_in_immutables: true - prefer_const_declarations: true - prefer_const_literals_to_create_immutables: true - prefer_contains: true - prefer_equal_for_default_values: true - prefer_final_fields: true - prefer_final_in_for_each: true - prefer_final_locals: true - prefer_for_elements_to_map_fromIterable: true - prefer_foreach: 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_null_aware_operators: true - prefer_single_quotes: true - prefer_spread_collections: true - prefer_typing_uninitialized_variables: true - prefer_void_to_null: true - provide_deprecation_message: true - recursive_getters: true - sized_box_for_whitespace: true - slash_for_doc_comments: true - sort_constructors_first: false # good for code readability but later - sort_unnamed_constructors_first: true - test_types_in_equals: true - throw_in_finally: true - tighten_type_of_initializing_formals: true - type_init_formals: true - unnecessary_await_in_return: true - unnecessary_brace_in_string_interps: true - unnecessary_const: true - unnecessary_getters_setters: 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_statements: true - unnecessary_string_escapes: true - unnecessary_string_interpolations: true - unnecessary_this: true - unrelated_type_equality_checks: true - use_full_hex_values_for_flutter_colors: true - use_function_type_syntax_for_parameters: true - use_is_even_rather_than_modulo: true - use_key_in_widget_constructors: false - use_late_for_private_fields_and_variables: true - use_named_constants: true - use_raw_strings: true - use_rethrow_when_possible: true - use_test_throws_matchers: true - valid_regexps: true - void_checks: false -dart_code_metrics: - extends: - - recommended - rules: - - avoid-shadowing: false # we shadow a lot, e.g. context in callbacks - - avoid-unsafe-collection-methods: false # we use foo[index] where index may not exist in theory, but in practice they will, in tests. also we can just handle the exceptions when they occur - - prefer-prefixed-global-constants: false # we don't really care for the 'k' prefix - - prefer-single-widget-per-file: false - - avoid-passing-self-as-argument: false # fairly harmless. and e.g. drift calls are like this - - avoid-passing-async-when-sync-expected: false # we really like to do this in onTap() etc, and it seems harmless - - prefer-match-file-name: false # dieter wants to enable this. but requires a lot of renames. what does roland think? + exclude: + - "**/*.g.dart" + - "**/generated/*" # Add the file to ignore here +fix: + data: + - always_put_required_named_parameters_first + - avoid_redundant_argument_values + - prefer_const_constructors + - use_key_in_widget_constructors - formatter: - indent: 0 - line-length: 100 - cascading-widget-extensions: false +dart: + code-actions-on-save: + source: + fix-all: true + organize-imports: true + fix-on-save: + - implicit-casts: false + fix: + sort-members: true + use-rational-asserts: true + # plugins: + # - custom_lint diff --git a/flatpak/scripts/flatpak_packager.dart b/flatpak/scripts/flatpak_packager.dart index 92cf27681..27cff0ccc 100644 --- a/flatpak/scripts/flatpak_packager.dart +++ b/flatpak/scripts/flatpak_packager.dart @@ -28,7 +28,8 @@ void main(List arguments) async { 'You must run this script with a metadata file argument, using the --meta flag.'); } if (arguments.length == metaIndex + 1) { - throw Exception('The --meta flag must be followed by the path to the metadata file.'); + throw Exception( + 'The --meta flag must be followed by the path to the metadata file.'); } final metaFile = File(arguments[metaIndex + 1]); @@ -39,8 +40,10 @@ void main(List arguments) async { final fetchFromGithub = arguments.contains('--github'); final addTodaysVersionIndex = arguments.indexOf('--addTodaysVersion'); - if (addTodaysVersionIndex != -1 && arguments.length == addTodaysVersionIndex + 1) { - throw Exception('The --addTodaysVersion flag must be followed by the version name.'); + if (addTodaysVersionIndex != -1 && + arguments.length == addTodaysVersionIndex + 1) { + throw Exception( + 'The --addTodaysVersion flag must be followed by the version name.'); } final addedTodaysVersion = @@ -48,17 +51,23 @@ void main(List arguments) async { // GENERATE PACKAGE - final meta = FlatpakMeta.fromJson(metaFile, skipLocalReleases: fetchFromGithub); + final meta = + FlatpakMeta.fromJson(metaFile, skipLocalReleases: fetchFromGithub); - final outputDir = Directory('${Directory.current.path}/flatpak_generator_exports'); + final outputDir = + Directory('${Directory.current.path}/flatpak_generator_exports'); await outputDir.create(); final packageGenerator = PackageGenerator( - inputDir: metaFile.parent, meta: meta, addedTodaysVersion: addedTodaysVersion); + inputDir: metaFile.parent, + meta: meta, + addedTodaysVersion: addedTodaysVersion); await packageGenerator.generatePackage( outputDir, - await PackageGenerator.runningOnARM() ? CPUArchitecture.aarch64 : CPUArchitecture.x86_64, + await PackageGenerator.runningOnARM() + ? CPUArchitecture.aarch64 + : CPUArchitecture.x86_64, fetchFromGithub); } @@ -67,10 +76,13 @@ class PackageGenerator { final FlatpakMeta meta; final String? addedTodaysVersion; - PackageGenerator({required this.inputDir, required this.meta, required this.addedTodaysVersion}); + PackageGenerator( + {required this.inputDir, + required this.meta, + required this.addedTodaysVersion}); - Future generatePackage( - Directory outputDir, CPUArchitecture arch, bool fetchReleasesFromGithub) async { + Future generatePackage(Directory outputDir, CPUArchitecture arch, + bool fetchReleasesFromGithub) async { final tempDir = await outputDir.createTemp('flutter_generator_temp'); final appId = meta.appId; @@ -122,12 +134,15 @@ class PackageGenerator { final destDir = Directory('${tempDir.path}/bin'); await destDir.create(); - final baseFilename = '${meta.lowercaseAppName}-linux-${arch.flatpakArchCode}'; + final baseFilename = + '${meta.lowercaseAppName}-linux-${arch.flatpakArchCode}'; final packagePath = '${outputDir.absolute.path}/$baseFilename.tar.gz'; final shaPath = '${outputDir.absolute.path}/$baseFilename.sha256'; - await Process.run('cp', ['-r', '${buildDir.absolute.path}/.', destDir.absolute.path]); - await Process.run('tar', ['-czvf', packagePath, '.'], workingDirectory: tempDir.absolute.path); + await Process.run( + 'cp', ['-r', '${buildDir.absolute.path}/.', destDir.absolute.path]); + await Process.run('tar', ['-czvf', packagePath, '.'], + workingDirectory: tempDir.absolute.path); print('Generated $packagePath'); @@ -150,10 +165,13 @@ class PackageGenerator { // updates releases in ${appName}.metainfo.xml class AppStreamModifier { - static String replaceVersions(String origAppStreamContent, List versions) { - final joinedReleases = - versions.map((v) => '\t\t').join('\n'); - final releasesSection = '\n$joinedReleases\n\t'; //TODO check this + static String replaceVersions( + String origAppStreamContent, List versions) { + final joinedReleases = versions + .map((v) => '\t\t') + .join('\n'); + final releasesSection = + '\n$joinedReleases\n\t'; //TODO check this if (origAppStreamContent.contains('') diff --git a/flatpak/scripts/flatpak_shared.dart b/flatpak/scripts/flatpak_shared.dart index 75ce96cf0..16f4931b2 100644 --- a/flatpak/scripts/flatpak_shared.dart +++ b/flatpak/scripts/flatpak_shared.dart @@ -44,8 +44,9 @@ class Icon { _fileExtension = path.split('.').last; } - String getFilename(String appId) => - (type == _symbolicType) ? '$appId-symbolic.$_fileExtension' : '$appId.$_fileExtension'; + String getFilename(String appId) => (type == _symbolicType) + ? '$appId-symbolic.$_fileExtension' + : '$appId.$_fileExtension'; } class GithubReleases { @@ -74,7 +75,8 @@ class GithubReleases { final releaseJsonContent = (await http.get(Uri( scheme: 'https', host: 'api.github.com', - path: '/repos/$githubReleaseOrganization/$githubReleaseProject/releases'))) + path: + '/repos/$githubReleaseOrganization/$githubReleaseProject/releases'))) .body; final decodedJson = jsonDecode(releaseJsonContent) as List; @@ -85,19 +87,23 @@ class GithubReleases { await Future.forEach(decodedJson, (dynamic releaseDynamic) async { final releaseMap = releaseDynamic as Map; - final releaseDateAndTime = DateTime.parse(releaseMap['published_at'] as String); - final releaseDateString = releaseDateAndTime.toIso8601String().split('T').first; + final releaseDateAndTime = + DateTime.parse(releaseMap['published_at'] as String); + final releaseDateString = + releaseDateAndTime.toIso8601String().split('T').first; if (latestReleaseAssetDate == null || (latestReleaseAssetDate?.compareTo(releaseDateAndTime) == -1)) { - final assets = await _parseGithubReleaseAssets(releaseMap['assets'] as List); + final assets = + await _parseGithubReleaseAssets(releaseMap['assets'] as List); if (assets != null) { _latestReleaseAssets = assets; latestReleaseAssetDate = releaseDateAndTime; } } - releases.add(Release(version: releaseMap['name'] as String, date: releaseDateString)); + releases.add(Release( + version: releaseMap['name'] as String, date: releaseDateString)); }); if (releases.isNotEmpty || canBeEmpty) { @@ -118,7 +124,8 @@ class GithubReleases { final downloadUrl = amMap['browser_download_url'] as String; final filename = amMap['name'] as String; final fileExtension = filename.substring(filename.indexOf('.') + 1); - final filenameWithoutExtension = filename.substring(0, filename.indexOf('.')); + final filenameWithoutExtension = + filename.substring(0, filename.indexOf('.')); final arch = filenameWithoutExtension.endsWith('aarch64') ? CPUArchitecture.aarch64 @@ -214,7 +221,8 @@ class FlatpakMeta { : _localReleases = localReleases, _localReleaseAssets = localReleaseAssets { if (githubReleaseOrganization != null && githubReleaseProject != null) { - _githubReleases = GithubReleases(githubReleaseOrganization!, githubReleaseProject!); + _githubReleases = + GithubReleases(githubReleaseOrganization!, githubReleaseProject!); } } @@ -223,17 +231,20 @@ class FlatpakMeta { final releases = List.empty(growable: true); if (addedTodaysVersion != null) { releases.add(Release( - version: addedTodaysVersion, date: DateTime.now().toIso8601String().split('T').first)); + version: addedTodaysVersion, + date: DateTime.now().toIso8601String().split('T').first)); } if (fetchReleasesFromGithub) { if (_githubReleases == null) { throw Exception( 'Metadata must include Github repository info if fetching releases from Github.'); } - releases.addAll(await _githubReleases!.getReleases(addedTodaysVersion != null)); + releases.addAll( + await _githubReleases!.getReleases(addedTodaysVersion != null)); } else { if (_localReleases == null && addedTodaysVersion == null) { - throw Exception('Metadata must include releases if not fetching releases from Github.'); + throw Exception( + 'Metadata must include releases if not fetching releases from Github.'); } if (_localReleases?.isNotEmpty ?? false) { releases.addAll(_localReleases!); @@ -242,7 +253,8 @@ class FlatpakMeta { return releases; } - Future?> getLatestReleaseAssets(bool fetchReleasesFromGithub) async { + Future?> getLatestReleaseAssets( + bool fetchReleasesFromGithub) async { if (fetchReleasesFromGithub) { if (_githubReleases == null) { throw Exception( @@ -251,7 +263,8 @@ class FlatpakMeta { return _githubReleases!.getLatestReleaseAssets(); } else { if (_localReleases == null) { - throw Exception('Metadata must include releases if not fetching releases from Github.'); + throw Exception( + 'Metadata must include releases if not fetching releases from Github.'); } return _localReleaseAssets; } @@ -263,20 +276,24 @@ class FlatpakMeta { return FlatpakMeta( appId: json['appId'] as String, lowercaseAppName: json['lowercaseAppName'] as String, - githubReleaseOrganization: json['githubReleaseOrganization'] as String?, + githubReleaseOrganization: + json['githubReleaseOrganization'] as String?, githubReleaseProject: json['githubReleaseProject'] as String?, localReleases: skipLocalReleases ? null : (json['localReleases'] as List?)?.map((dynamic r) { final rMap = r as Map; - return Release(version: rMap['version'] as String, date: rMap['date'] as String); + return Release( + version: rMap['version'] as String, + date: rMap['date'] as String); }).toList(), localReleaseAssets: skipLocalReleases ? null : (json['localReleaseAssets'] as List?)?.map((dynamic ra) { final raMap = ra as Map; final archString = raMap['arch'] as String; - final arch = (archString == CPUArchitecture.x86_64.flatpakArchCode) + final arch = (archString == + CPUArchitecture.x86_64.flatpakArchCode) ? CPUArchitecture.x86_64 : (archString == CPUArchitecture.aarch64.flatpakArchCode) ? CPUArchitecture.aarch64 @@ -285,10 +302,11 @@ class FlatpakMeta { throw Exception( 'Architecture must be either "${CPUArchitecture.x86_64.flatpakArchCode}" or "${CPUArchitecture.aarch64.flatpakArchCode}"'); } - final tarballFile = - File('${jsonFile.parent.path}/${raMap['tarballPath'] as String}'); + final tarballFile = File( + '${jsonFile.parent.path}/${raMap['tarballPath'] as String}'); final tarballPath = tarballFile.absolute.path; - final preShasum = Process.runSync('shasum', ['-a', '256', tarballPath]); + final preShasum = + Process.runSync('shasum', ['-a', '256', tarballPath]); final shasum = preShasum.stdout.toString().split(' ').first; if (preShasum.exitCode != 0) { throw Exception(preShasum.stderr); @@ -303,14 +321,17 @@ class FlatpakMeta { appStreamPath: json['appStreamPath'] as String, desktopPath: json['desktopPath'] as String, icons: (json['icons'] as Map).entries.map((mapEntry) { - return Icon(type: mapEntry.key as String, path: mapEntry.value as String); + return Icon( + type: mapEntry.key as String, path: mapEntry.value as String); }).toList(), freedesktopRuntime: json['freedesktopRuntime'] as String, buildCommandsAfterUnpack: (json['buildCommandsAfterUnpack'] as List?) ?.map((dynamic bc) => bc as String) .toList(), extraModules: json['extraModules'] as List?, - finishArgs: (json['finishArgs'] as List).map((dynamic fa) => fa as String).toList()); + finishArgs: (json['finishArgs'] as List) + .map((dynamic fa) => fa as String) + .toList()); } catch (e) { throw Exception('Could not parse JSON file, due to this error:\n$e'); } diff --git a/flatpak/scripts/manifest_generator.dart b/flatpak/scripts/manifest_generator.dart index 254bb1aec..8957a3d16 100644 --- a/flatpak/scripts/manifest_generator.dart +++ b/flatpak/scripts/manifest_generator.dart @@ -26,7 +26,8 @@ void main(List arguments) async { 'You must run this script with a metadata file argument, using the --meta flag.'); } if (arguments.length == metaIndex + 1) { - throw Exception('The --meta flag must be followed by the path to the metadata file.'); + throw Exception( + 'The --meta flag must be followed by the path to the metadata file.'); } final metaFile = File(arguments[metaIndex + 1]); @@ -36,19 +37,23 @@ void main(List arguments) async { final fetchFromGithub = arguments.contains('--github'); - final meta = FlatpakMeta.fromJson(metaFile, skipLocalReleases: fetchFromGithub); + final meta = + FlatpakMeta.fromJson(metaFile, skipLocalReleases: fetchFromGithub); - final outputDir = Directory('${Directory.current.path}/flatpak_generator_exports'); + final outputDir = + Directory('${Directory.current.path}/flatpak_generator_exports'); outputDir.createSync(); final manifestGenerator = FlatpakManifestGenerator(meta); - final manifestContent = await manifestGenerator.generateFlatpakManifest(fetchFromGithub); + final manifestContent = + await manifestGenerator.generateFlatpakManifest(fetchFromGithub); final manifestPath = '${outputDir.path}/${meta.appId}.json'; final manifestFile = File(manifestPath); manifestFile.writeAsStringSync(manifestContent); print('Generated $manifestPath'); - final flathubJsonContent = await manifestGenerator.generateFlathubJson(fetchFromGithub); + final flathubJsonContent = + await manifestGenerator.generateFlathubJson(fetchFromGithub); if (flathubJsonContent != null) { final flathubJsonPath = '${outputDir.path}/flathub.json'; final flathubJsonFile = File(flathubJsonPath); @@ -127,7 +132,8 @@ class FlatpakManifestGenerator { const encoder = JsonEncoder.withIndent(' '); - final onlyArchListInput = fetchFromGithub ? _githubArchSupport! : _localArchSupport!; + final onlyArchListInput = + fetchFromGithub ? _githubArchSupport! : _localArchSupport!; final onlyArchList = List.empty(growable: true); for (final e in onlyArchListInput.entries) { @@ -143,7 +149,8 @@ class FlatpakManifestGenerator { } } - void _lazyGenerateArchSupportMap(bool fetchFromGithub, List assets) { + void _lazyGenerateArchSupportMap( + bool fetchFromGithub, List assets) { if (fetchFromGithub) { if (_githubArchSupport == null) { _githubArchSupport = { diff --git a/integration_test/1_dashboard.dart b/integration_test/dashboard_widget.dart similarity index 88% rename from integration_test/1_dashboard.dart rename to integration_test/dashboard_widget.dart index 4550fea77..dc42092a6 100644 --- a/integration_test/1_dashboard.dart +++ b/integration_test/dashboard_widget.dart @@ -24,7 +24,8 @@ import '../test_data/workouts.dart'; Widget createDashboardScreen({locale = 'en'}) { final mockWorkoutProvider = MockWorkoutPlansProvider(); - when(mockWorkoutProvider.activePlan).thenReturn(getWorkout(exercises: getScreenshotExercises())); + when(mockWorkoutProvider.activePlan) + .thenReturn(getWorkout(exercises: getScreenshotExercises())); final Map logs = { 'results': [ @@ -38,19 +39,22 @@ Widget createDashboardScreen({locale = 'en'}) { }, ], }; - when(mockWorkoutProvider.fetchSessionData()).thenAnswer((a) => Future.value(logs)); + when(mockWorkoutProvider.fetchSessionData()) + .thenAnswer((a) => Future.value(logs)); final mockNutritionProvider = MockNutritionPlansProvider(); when(mockNutritionProvider.currentPlan) .thenAnswer((realInvocation) => getNutritionalPlanScreenshot()); - when(mockNutritionProvider.items).thenReturn([getNutritionalPlanScreenshot()]); + when(mockNutritionProvider.items) + .thenReturn([getNutritionalPlanScreenshot()]); final mockWeightProvider = MockBodyWeightProvider(); when(mockWeightProvider.items).thenReturn(getScreenshotWeightEntries()); final mockMeasurementProvider = MockMeasurementProvider(); - when(mockMeasurementProvider.categories).thenReturn(getMeasurementCategories()); + when(mockMeasurementProvider.categories) + .thenReturn(getMeasurementCategories()); final mockUserProvider = MockUserProvider(); when(mockUserProvider.profile).thenReturn(tProfile1); diff --git a/integration_test/3_gym_mode.dart b/integration_test/gym_mode_widget.dart similarity index 91% rename from integration_test/3_gym_mode.dart rename to integration_test/gym_mode_widget.dart index 202b7c299..a6c96c683 100644 --- a/integration_test/3_gym_mode.dart +++ b/integration_test/gym_mode_widget.dart @@ -20,8 +20,10 @@ Widget createGymModeScreen({locale = 'en'}) { final mockExerciseProvider = MockExercisesProvider(); - when(mockExerciseProvider.findExerciseById(1)).thenReturn(bases[0]); // bench press - when(mockExerciseProvider.findExerciseById(6)).thenReturn(bases[5]); // side raises + when(mockExerciseProvider.findExerciseById(1)) + .thenReturn(bases[0]); // bench press + when(mockExerciseProvider.findExerciseById(6)) + .thenReturn(bases[5]); // side raises //when(mockExerciseProvider.findExerciseBaseById(2)).thenReturn(bases[1]); // crunches //when(mockExerciseProvider.findExerciseBaseById(3)).thenReturn(bases[2]); // dead lift diff --git a/integration_test/make_screenshots_test.dart b/integration_test/make_screenshots_test.dart index 3d8c7f48d..3846dc96e 100644 --- a/integration_test/make_screenshots_test.dart +++ b/integration_test/make_screenshots_test.dart @@ -4,12 +4,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; -import '1_dashboard.dart'; -import '2_workout.dart'; -import '3_gym_mode.dart'; -import '4_measurements.dart'; -import '5_nutritional_plan.dart'; -import '6_weight.dart'; +import 'dashboard_widget.dart'; +import 'gym_mode_widget.dart'; +import 'measurements_widget.dart'; +import 'nutritional_plan_widget.dart'; +import 'weight_widget.dart'; +import 'workout_widget.dart'; // Type of device enum DeviceType { @@ -22,13 +22,15 @@ enum DeviceType { final destination = DeviceType.tenInchScreenshots.name; -Future takeScreenshot(tester, binding, String language, String name) async { +Future takeScreenshot( + tester, binding, String language, String name) async { if (Platform.isAndroid) { await tester.pumpAndSettle(); await binding.convertFlutterSurfaceToImage(); await tester.pumpAndSettle(); } - final filename = 'fastlane/metadata/android/$language/images/$destination/$name.png'; + final filename = + 'fastlane/metadata/android/$language/images/$destination/$name.png'; await binding.takeScreenshot(filename); } @@ -72,8 +74,10 @@ void main() { await takeScreenshot(tester, binding, language, '01 - dashboard'); }); - testWidgets('workout detail screen - $language', (WidgetTester tester) async { - await tester.pumpWidget(createWorkoutDetailScreen(locale: languageCode)); + testWidgets('workout detail screen - $language', + (WidgetTester tester) async { + await tester + .pumpWidget(createWorkoutDetailScreen(locale: languageCode)); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); await takeScreenshot(tester, binding, language, '02 - workout detail'); @@ -86,19 +90,24 @@ void main() { await takeScreenshot(tester, binding, language, '03 - gym mode'); }); - testWidgets('measurement screen - $language', (WidgetTester tester) async { + testWidgets('measurement screen - $language', + (WidgetTester tester) async { await tester.pumpWidget(createMeasurementScreen(locale: languageCode)); await takeScreenshot(tester, binding, language, '04 - measurements'); }); - testWidgets('nutritional plan detail - $language', (WidgetTester tester) async { - await tester.pumpWidget(createNutritionalPlanScreen(locale: languageCode)); + testWidgets('nutritional plan detail - $language', + (WidgetTester tester) async { + await tester + .pumpWidget(createNutritionalPlanScreen(locale: languageCode)); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); - await takeScreenshot(tester, binding, language, '05 - nutritional plan'); + await takeScreenshot( + tester, binding, language, '05 - nutritional plan'); }); - testWidgets('body weight screen - $language', (WidgetTester tester) async { + testWidgets('body weight screen - $language', + (WidgetTester tester) async { await tester.pumpWidget(createWeightScreen(locale: languageCode)); await tester.pumpAndSettle(); await takeScreenshot(tester, binding, language, '06 - weight'); diff --git a/integration_test/4_measurements.dart b/integration_test/measurements_widget.dart similarity index 92% rename from integration_test/4_measurements.dart rename to integration_test/measurements_widget.dart index 8db33ba0d..9ef60d9ec 100644 --- a/integration_test/4_measurements.dart +++ b/integration_test/measurements_widget.dart @@ -11,7 +11,8 @@ import '../test_data/measurements.dart'; Widget createMeasurementScreen({locale = 'en'}) { final mockMeasurementProvider = MockMeasurementProvider(); - when(mockMeasurementProvider.categories).thenReturn(getMeasurementCategories()); + when(mockMeasurementProvider.categories) + .thenReturn(getMeasurementCategories()); return MultiProvider( providers: [ diff --git a/integration_test/5_nutritional_plan.dart b/integration_test/nutritional_plan_widget.dart similarity index 100% rename from integration_test/5_nutritional_plan.dart rename to integration_test/nutritional_plan_widget.dart diff --git a/integration_test/6_weight.dart b/integration_test/weight_widget.dart similarity index 100% rename from integration_test/6_weight.dart rename to integration_test/weight_widget.dart diff --git a/integration_test/2_workout.dart b/integration_test/workout_widget.dart similarity index 93% rename from integration_test/2_workout.dart rename to integration_test/workout_widget.dart index 96bad963c..eb9f6a38d 100644 --- a/integration_test/2_workout.dart +++ b/integration_test/workout_widget.dart @@ -16,7 +16,8 @@ Widget createWorkoutDetailScreen({locale = 'en'}) { final mockWorkoutProvider = MockWorkoutPlansProvider(); final workout = getWorkout(exercises: getScreenshotExercises()); when(mockWorkoutProvider.activePlan).thenReturn(workout); - when(mockWorkoutProvider.fetchAndSetWorkoutPlanFull(1)).thenAnswer((_) => Future.value(workout)); + when(mockWorkoutProvider.fetchAndSetWorkoutPlanFull(1)) + .thenAnswer((_) => Future.value(workout)); return MultiProvider( providers: [ diff --git a/lib/database/exercises/type_converters.dart b/lib/database/exercises/type_converters.dart index b494aa2aa..200fa9065 100644 --- a/lib/database/exercises/type_converters.dart +++ b/lib/database/exercises/type_converters.dart @@ -21,24 +21,30 @@ class ExerciseBaseConverter extends TypeConverter { final Map baseData = json.decode(fromDb); final category = ExerciseCategory.fromJson(baseData['categories']); - final musclesPrimary = baseData['muscless'].map((e) => Muscle.fromJson(e)).toList(); - final musclesSecondary = baseData['musclesSecondary'].map((e) => Muscle.fromJson(e)).toList(); - final equipment = baseData['equipments'].map((e) => Equipment.fromJson(e)).toList(); - final images = baseData['images'].map((e) => ExerciseImage.fromJson(e)).toList(); + final musclesPrimary = + baseData['muscless'].map((e) => Muscle.fromJson(e)).toList(); + final musclesSecondary = + baseData['musclesSecondary'].map((e) => Muscle.fromJson(e)).toList(); + final equipment = + baseData['equipments'].map((e) => Equipment.fromJson(e)).toList(); + final images = + baseData['images'].map((e) => ExerciseImage.fromJson(e)).toList(); final videos = baseData['videos'].map((e) => Video.fromJson(e)).toList(); final List translations = []; for (final exerciseData in baseData['translations']) { final translation = Translation( - id: exerciseData['id'], - name: exerciseData['name'], - description: exerciseData['description'], - exerciseId: baseData['id'], - ); - translation.aliases = exerciseData['aliases'].map((e) => Alias.fromJson(e)).toList(); - translation.notes = exerciseData['notes'].map((e) => Comment.fromJson(e)).toList(); - translation.language = Language.fromJson(exerciseData['languageObj']); - translations.add(translation); + id: exerciseData['id'], + name: exerciseData['name'], + description: exerciseData['description'], + exerciseId: baseData['id'], + languageId: Language.fromJson(exerciseData['languageObj']).id, + languageObj: Language.fromJson(exerciseData['languageObj'])); + + translations.add(translation.copyWith( + aliases: exerciseData['aliases'].map((e) => Alias.fromJson(e)).toList(), + notes: exerciseData['notes'].map((e) => Comment.fromJson(e)).toList(), + )); } final exerciseBase = Exercise( @@ -91,12 +97,14 @@ class EquipmentConverter extends TypeConverter { } } -class ExerciseCategoryConverter extends TypeConverter { +class ExerciseCategoryConverter + extends TypeConverter { const ExerciseCategoryConverter(); @override ExerciseCategory fromSql(String fromDb) { - return ExerciseCategory.fromJson(json.decode(fromDb) as Map); + return ExerciseCategory.fromJson( + json.decode(fromDb) as Map); } @override diff --git a/lib/exceptions/http_exception.dart b/lib/exceptions/http_exception.dart index ca38f0a22..9b0b6fb19 100644 --- a/lib/exceptions/http_exception.dart +++ b/lib/exceptions/http_exception.dart @@ -26,11 +26,15 @@ class WgerHttpException implements Exception { /// JSON. Will use the response as-is if it fails. WgerHttpException(dynamic responseBody) { if (responseBody == null) { - errors = {'unknown_error': 'An unknown error occurred, no further information available'}; + errors = { + 'unknown_error': + 'An unknown error occurred, no further information available' + }; } else { try { final response = json.decode(responseBody); - errors = (response is Map ? response : {'unknown_error': response}).cast(); + errors = (response is Map ? response : {'unknown_error': response}) + .cast(); } catch (e) { errors = {'unknown_error': responseBody}; } diff --git a/lib/helpers/charts.dart b/lib/helpers/charts.dart index 64a0b6e84..9b7584377 100644 --- a/lib/helpers/charts.dart +++ b/lib/helpers/charts.dart @@ -1,5 +1,7 @@ double chartGetInterval(DateTime first, DateTime last, {divider = 3}) { final dayDiff = last.difference(first); - return dayDiff.inMilliseconds == 0 ? 1000 : dayDiff.inMilliseconds.abs() / divider; + return dayDiff.inMilliseconds == 0 + ? 1000 + : dayDiff.inMilliseconds.abs() / divider; } diff --git a/lib/helpers/exercises/forms.dart b/lib/helpers/exercises/forms.dart index 25d92bde4..6e05d93c8 100644 --- a/lib/helpers/exercises/forms.dart +++ b/lib/helpers/exercises/forms.dart @@ -14,7 +14,8 @@ String? validateName(String? name, BuildContext context) { } if (name.length < MIN_CHARS_NAME || name.length > MAX_CHARS_NAME) { - return AppLocalizations.of(context).enterCharacters(MIN_CHARS_NAME, MAX_CHARS_NAME); + return AppLocalizations.of(context) + .enterCharacters(MIN_CHARS_NAME, MAX_CHARS_NAME); } return null; @@ -26,7 +27,8 @@ String? validateDescription(String? name, BuildContext context) { } if (name.length < MIN_CHARS_DESCRIPTION) { - return AppLocalizations.of(context).enterMinCharacters(MIN_CHARS_DESCRIPTION); + return AppLocalizations.of(context) + .enterMinCharacters(MIN_CHARS_DESCRIPTION); } return null; diff --git a/lib/helpers/json.dart b/lib/helpers/json.dart index bca181948..28438d576 100644 --- a/lib/helpers/json.dart +++ b/lib/helpers/json.dart @@ -58,5 +58,6 @@ String? timeToString(TimeOfDay? time) { if (time == null) { return null; } - return const DefaultMaterialLocalizations().formatTimeOfDay(time, alwaysUse24HourFormat: true); + return const DefaultMaterialLocalizations() + .formatTimeOfDay(time, alwaysUse24HourFormat: true); } diff --git a/lib/helpers/misc.dart b/lib/helpers/misc.dart index b880e8c2d..c1fbafea0 100644 --- a/lib/helpers/misc.dart +++ b/lib/helpers/misc.dart @@ -42,7 +42,9 @@ String repText( // rather "8 repetitions". If there is weight we want to output "8 x 50kg", // since the repetitions are implied. If other units are used, we always // print them - if (repetitionUnitObj.id != REP_UNIT_REPETITIONS || weight == 0 || weight == null) { + if (repetitionUnitObj.id != REP_UNIT_REPETITIONS || + weight == 0 || + weight == null) { out.add(repetitionUnitObj.name); } } diff --git a/lib/helpers/platform.dart b/lib/helpers/platform.dart index 82b0484d7..6d8573783 100644 --- a/lib/helpers/platform.dart +++ b/lib/helpers/platform.dart @@ -21,4 +21,5 @@ import 'package:flutter/foundation.dart'; // Note: we're not using Platform.isAndroid etc because during tests these would+ // always take the value of the current platform. TargetPlatform is always Android // during tests, but can be changed to check for correct UI switches, etc. -final isDesktop = [TargetPlatform.linux, TargetPlatform.macOS].contains(defaultTargetPlatform); +final isDesktop = [TargetPlatform.linux, TargetPlatform.macOS] + .contains(defaultTargetPlatform); diff --git a/lib/helpers/ui.dart b/lib/helpers/ui.dart index 7e8823e56..00c5a77e8 100644 --- a/lib/helpers/ui.dart +++ b/lib/helpers/ui.dart @@ -63,7 +63,8 @@ void showHttpExceptionErrorDialog( for (final key in exception.errors!.keys) { // Error headers // Ensure that the error heading first letter is capitalized. - final String errorHeaderMsg = key[0].toUpperCase() + key.substring(1, key.length); + final String errorHeaderMsg = + key[0].toUpperCase() + key.substring(1, key.length); errorList.add( Text( @@ -134,7 +135,8 @@ dynamic showDeleteDialog( ), onPressed: () { exerciseData[exercise]!.removeWhere((el) => el.id == log.id); - Provider.of(context, listen: false).deleteLog( + Provider.of(context, listen: false) + .deleteLog( log, ); diff --git a/lib/main.dart b/lib/main.dart index ac4abfe1a..3226c987f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -81,14 +81,16 @@ class MyApp extends StatelessWidget { update: (context, base, previous) => previous ?? ExercisesProvider(WgerBaseProvider(base)), ), - ChangeNotifierProxyProvider2( + ChangeNotifierProxyProvider2( create: (context) => WorkoutPlansProvider( WgerBaseProvider(Provider.of(context, listen: false)), Provider.of(context, listen: false), [], ), update: (context, auth, exercises, previous) => - previous ?? WorkoutPlansProvider(WgerBaseProvider(auth), exercises, []), + previous ?? + WorkoutPlansProvider(WgerBaseProvider(auth), exercises, []), ), ChangeNotifierProxyProvider( create: (context) => NutritionPlansProvider( @@ -109,7 +111,8 @@ class MyApp extends StatelessWidget { create: (context) => UserProvider( WgerBaseProvider(Provider.of(context, listen: false)), ), - update: (context, base, previous) => previous ?? UserProvider(WgerBaseProvider(base)), + update: (context, base, previous) => + previous ?? UserProvider(WgerBaseProvider(base)), ), ChangeNotifierProxyProvider( create: (context) => BodyWeightProvider( @@ -123,7 +126,8 @@ class MyApp extends StatelessWidget { Provider.of(context, listen: false), [], ), - update: (context, auth, previous) => previous ?? GalleryProvider(auth, []), + update: (context, auth, previous) => + previous ?? GalleryProvider(auth, []), ), ChangeNotifierProxyProvider( create: (context) => AddExerciseProvider( @@ -146,7 +150,8 @@ class MyApp extends StatelessWidget { : FutureBuilder( future: auth.tryAutoLogin(), builder: (ctx, authResultSnapshot) => - authResultSnapshot.connectionState == ConnectionState.waiting + authResultSnapshot.connectionState == + ConnectionState.waiting ? const SplashScreen() : const AuthScreen(), ), @@ -156,18 +161,24 @@ class MyApp extends StatelessWidget { GalleryScreen.routeName: (ctx) => const GalleryScreen(), GymModeScreen.routeName: (ctx) => const GymModeScreen(), HomeTabsScreen.routeName: (ctx) => const HomeTabsScreen(), - MeasurementCategoriesScreen.routeName: (ctx) => const MeasurementCategoriesScreen(), - MeasurementEntriesScreen.routeName: (ctx) => const MeasurementEntriesScreen(), - NutritionalPlansScreen.routeName: (ctx) => const NutritionalPlansScreen(), - NutritionalDiaryScreen.routeName: (ctx) => const NutritionalDiaryScreen(), - NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(), + MeasurementCategoriesScreen.routeName: (ctx) => + const MeasurementCategoriesScreen(), + MeasurementEntriesScreen.routeName: (ctx) => + const MeasurementEntriesScreen(), + NutritionalPlansScreen.routeName: (ctx) => + const NutritionalPlansScreen(), + NutritionalDiaryScreen.routeName: (ctx) => + const NutritionalDiaryScreen(), + NutritionalPlanScreen.routeName: (ctx) => + const NutritionalPlanScreen(), LogMealsScreen.routeName: (ctx) => const LogMealsScreen(), LogMealScreen.routeName: (ctx) => const LogMealScreen(), WeightScreen.routeName: (ctx) => const WeightScreen(), WorkoutPlanScreen.routeName: (ctx) => const WorkoutPlanScreen(), WorkoutPlansScreen.routeName: (ctx) => const WorkoutPlansScreen(), ExercisesScreen.routeName: (ctx) => const ExercisesScreen(), - ExerciseDetailScreen.routeName: (ctx) => const ExerciseDetailScreen(), + ExerciseDetailScreen.routeName: (ctx) => + const ExerciseDetailScreen(), AddExerciseScreen.routeName: (ctx) => const AddExerciseScreen(), AboutPage.routeName: (ctx) => const AboutPage(), SettingsPage.routeName: (ctx) => const SettingsPage(), diff --git a/lib/models/body_weight/weight_entry.dart b/lib/models/body_weight/weight_entry.dart index 47c8be9fa..dd7aeadda 100644 --- a/lib/models/body_weight/weight_entry.dart +++ b/lib/models/body_weight/weight_entry.dart @@ -47,7 +47,8 @@ class WeightEntry { ); // Boilerplate - factory WeightEntry.fromJson(Map json) => _$WeightEntryFromJson(json); + factory WeightEntry.fromJson(Map json) => + _$WeightEntryFromJson(json); Map toJson() => _$WeightEntryToJson(this); } diff --git a/lib/models/exercises/category.dart b/lib/models/exercises/category.dart index 90add14e9..d5f51b5ce 100644 --- a/lib/models/exercises/category.dart +++ b/lib/models/exercises/category.dart @@ -37,7 +37,8 @@ class ExerciseCategory extends Equatable { } // Boilerplate - factory ExerciseCategory.fromJson(Map json) => _$ExerciseCategoryFromJson(json); + factory ExerciseCategory.fromJson(Map json) => + _$ExerciseCategoryFromJson(json); Map toJson() => _$ExerciseCategoryToJson(this); @override diff --git a/lib/models/exercises/comment.dart b/lib/models/exercises/comment.dart index 5fb5fc58c..50acb7cfe 100644 --- a/lib/models/exercises/comment.dart +++ b/lib/models/exercises/comment.dart @@ -38,6 +38,7 @@ class Comment { }); // Boilerplate - factory Comment.fromJson(Map json) => _$CommentFromJson(json); + factory Comment.fromJson(Map json) => + _$CommentFromJson(json); Map toJson() => _$CommentToJson(this); } diff --git a/lib/models/exercises/equipment.dart b/lib/models/exercises/equipment.dart index 6f565457f..2499991e9 100644 --- a/lib/models/exercises/equipment.dart +++ b/lib/models/exercises/equipment.dart @@ -32,7 +32,8 @@ class Equipment extends Equatable { const Equipment({required this.id, required this.name}); // Boilerplate - factory Equipment.fromJson(Map json) => _$EquipmentFromJson(json); + factory Equipment.fromJson(Map json) => + _$EquipmentFromJson(json); Map toJson() => _$EquipmentToJson(this); @override diff --git a/lib/models/exercises/exercise.dart b/lib/models/exercises/exercise.dart index 2929dce92..05995fdde 100644 --- a/lib/models/exercises/exercise.dart +++ b/lib/models/exercises/exercise.dart @@ -31,6 +31,7 @@ import 'package:wger/models/exercises/video.dart'; part 'exercise.g.dart'; @JsonSerializable(explicitToJson: true) +// ignore: must_be_immutable class Exercise extends Equatable { @JsonKey(required: true) late final int? id; @@ -142,7 +143,8 @@ class Exercise extends Equatable { Exercise.fromApiDataString(String baseData, List languages) : this.fromApiData(ExerciseApiData.fromString(baseData), languages); - Exercise.fromApiDataJson(Map baseData, List languages) + Exercise.fromApiDataJson( + Map baseData, List languages) : this.fromApiData(ExerciseApiData.fromJson(baseData), languages); Exercise.fromApiData(ExerciseApiData baseData, List languages) { @@ -160,8 +162,10 @@ class Exercise extends Equatable { equipment = baseData.equipment; category = baseData.category; translations = baseData.translations.map((e) { - e.language = languages.firstWhere((l) => l.id == e.languageId); - return e; + return e.copyWith( + languageObj: languages.firstWhere((l) => l.id == e.languageId), + languageId: e.languageId, + ); }).toList(); videos = baseData.videos; images = baseData.images; @@ -185,9 +189,9 @@ class Exercise extends Equatable { final languageCode = language.split('-')[0]; return translations.firstWhere( - (e) => e.languageObj.shortName == languageCode, + (e) => e.languageObj?.shortName == languageCode, orElse: () => translations.firstWhere( - (e) => e.languageObj.shortName == LANGUAGE_SHORT_ENGLISH, + (e) => e.languageObj?.shortName == LANGUAGE_SHORT_ENGLISH, orElse: () => translations.first, ), ); @@ -207,7 +211,8 @@ class Exercise extends Equatable { } // Boilerplate - factory Exercise.fromJson(Map json) => _$ExerciseFromJson(json); + factory Exercise.fromJson(Map json) => + _$ExerciseFromJson(json); Map toJson() => _$ExerciseToJson(this); diff --git a/lib/models/exercises/exercise_api.dart b/lib/models/exercises/exercise_api.dart index fb9c36e08..02c6ba61f 100644 --- a/lib/models/exercises/exercise_api.dart +++ b/lib/models/exercises/exercise_api.dart @@ -44,9 +44,11 @@ class ExerciseApiData with _$ExerciseApiData { @JsonKey(name: 'total_authors_history') required List authorsGlobal, }) = _ExerciseBaseData; - factory ExerciseApiData.fromString(String input) => _$ExerciseApiDataFromJson(json.decode(input)); + factory ExerciseApiData.fromString(String input) => + _$ExerciseApiDataFromJson(json.decode(input)); - factory ExerciseApiData.fromJson(Map json) => _$ExerciseApiDataFromJson(json); + factory ExerciseApiData.fromJson(Map json) => + _$ExerciseApiDataFromJson(json); } /// Model for the search results returned from the /api/v2/exercise/search endpoint diff --git a/lib/models/exercises/image.dart b/lib/models/exercises/image.dart index d9b5dff9d..e3be4917d 100644 --- a/lib/models/exercises/image.dart +++ b/lib/models/exercises/image.dart @@ -46,7 +46,8 @@ class ExerciseImage { }); // Boilerplate - factory ExerciseImage.fromJson(Map json) => _$ExerciseImageFromJson(json); + factory ExerciseImage.fromJson(Map json) => + _$ExerciseImageFromJson(json); Map toJson() => _$ExerciseImageToJson(this); @override diff --git a/lib/models/exercises/language.dart b/lib/models/exercises/language.dart index 23f048567..3e72986de 100644 --- a/lib/models/exercises/language.dart +++ b/lib/models/exercises/language.dart @@ -39,7 +39,8 @@ class Language extends Equatable { }); // Boilerplate - factory Language.fromJson(Map json) => _$LanguageFromJson(json); + factory Language.fromJson(Map json) => + _$LanguageFromJson(json); Map toJson() => _$LanguageToJson(this); @override diff --git a/lib/models/exercises/muscle.dart b/lib/models/exercises/muscle.dart index abb6bbbf3..134c462e6 100644 --- a/lib/models/exercises/muscle.dart +++ b/lib/models/exercises/muscle.dart @@ -53,7 +53,8 @@ class Muscle extends Equatable { List get props => [id, name, isFront]; String nameTranslated(BuildContext context) { - return name + (nameEn.isNotEmpty ? ' (${getTranslation(nameEn, context)})' : ''); + return name + + (nameEn.isNotEmpty ? ' (${getTranslation(nameEn, context)})' : ''); } @override diff --git a/lib/models/exercises/translation.dart b/lib/models/exercises/translation.dart index d7a3775d0..68e11c403 100644 --- a/lib/models/exercises/translation.dart +++ b/lib/models/exercises/translation.dart @@ -20,7 +20,6 @@ import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:wger/models/exercises/alias.dart'; import 'package:wger/models/exercises/comment.dart'; -import 'package:wger/models/exercises/exercise.dart'; import 'package:wger/models/exercises/language.dart'; part 'translation.g.dart'; @@ -34,16 +33,16 @@ class Translation extends Equatable { final String? uuid; @JsonKey(required: true, name: 'language') - late int languageId; + final int languageId; @JsonKey(includeFromJson: false, includeToJson: false) - late Language languageObj; + final Language? languageObj; @JsonKey(required: true, name: 'created') final DateTime? created; @JsonKey(required: true, name: 'exercise_base') - late int? exerciseId; + final int? exerciseId; @JsonKey(required: true) final String name; @@ -52,52 +51,82 @@ class Translation extends Equatable { final String description; @JsonKey(includeFromJson: true, includeToJson: false) - List notes = []; + final List notes; @JsonKey(includeFromJson: true, includeToJson: false) - List aliases = []; + final List aliases; - Translation({ + const Translation({ this.id, this.uuid, this.created, required this.name, required this.description, - int? exerciseId, - language, - }) { - if (exerciseId != null) { - this.exerciseId = exerciseId; - } - - if (language != null) { - languageObj = language; - languageId = language.id; - } - } - - set exercise(Exercise exercise) { - exerciseId = exercise.id; - } - - set language(Language language) { - languageObj = language; - languageId = language.id; - } + required this.languageId, + this.languageObj, + this.exerciseId, + this.notes = const [], + this.aliases = const [], + }); // Boilerplate - factory Translation.fromJson(Map json) => _$TranslationFromJson(json); + factory Translation.fromJson(Map json) => + _$TranslationFromJson(json); Map toJson() => _$TranslationToJson(this); @override List get props => [ id, - exerciseId, uuid, languageId, created, + exerciseId, name, description, + notes, + aliases, ]; + + Translation copyWith({ + int? id, + String? uuid, + DateTime? created, + String? name, + String? description, + int? languageId, + Language? languageObj, + int? exerciseId, + List? notes, + List? aliases, + }) { + return Translation( + id: id ?? this.id, + uuid: uuid ?? this.uuid, + created: created ?? this.created, + name: name ?? this.name, + description: description ?? this.description, + languageId: languageId ?? this.languageId, + languageObj: languageObj ?? this.languageObj, + exerciseId: exerciseId ?? this.exerciseId, + notes: notes ?? this.notes, + aliases: aliases ?? this.aliases, + ); + } + + // Helper to associate languageObj after deserialization + Translation withLanguageObj(Language language) { + return Translation( + id: id, + uuid: uuid, + created: created, + name: name, + description: description, + languageId: languageId, + languageObj: language, + exerciseId: exerciseId, + notes: notes, + aliases: aliases, + ); + } } diff --git a/lib/models/exercises/translation.g.dart b/lib/models/exercises/translation.g.dart index e308dc10f..1f401dde0 100644 --- a/lib/models/exercises/translation.g.dart +++ b/lib/models/exercises/translation.g.dart @@ -27,15 +27,17 @@ Translation _$TranslationFromJson(Map json) { : DateTime.parse(json['created'] as String), name: json['name'] as String, description: json['description'] as String, + languageId: (json['language'] as num).toInt(), exerciseId: (json['exercise_base'] as num?)?.toInt(), - ) - ..languageId = (json['language'] as num).toInt() - ..notes = (json['notes'] as List) - .map((e) => Comment.fromJson(e as Map)) - .toList() - ..aliases = (json['aliases'] as List) - .map((e) => Alias.fromJson(e as Map)) - .toList(); + notes: (json['notes'] as List?) + ?.map((e) => Comment.fromJson(e as Map)) + .toList() ?? + const [], + aliases: (json['aliases'] as List?) + ?.map((e) => Alias.fromJson(e as Map)) + .toList() ?? + const [], + ); } Map _$TranslationToJson(Translation instance) => diff --git a/lib/models/exercises/variation.dart b/lib/models/exercises/variation.dart index 7d069494d..23d68cefb 100644 --- a/lib/models/exercises/variation.dart +++ b/lib/models/exercises/variation.dart @@ -28,6 +28,7 @@ class Variation { const Variation({required this.id}); // Boilerplate - factory Variation.fromJson(Map json) => _$VariationFromJson(json); + factory Variation.fromJson(Map json) => + _$VariationFromJson(json); Map toJson() => _$VariationToJson(this); } diff --git a/lib/models/measurements/measurement_entry.dart b/lib/models/measurements/measurement_entry.dart index dd24b05e1..04c27dddb 100644 --- a/lib/models/measurements/measurement_entry.dart +++ b/lib/models/measurements/measurement_entry.dart @@ -29,7 +29,12 @@ class MeasurementEntry extends Equatable { required this.notes, }); - MeasurementEntry copyWith({int? id, int? category, DateTime? date, num? value, String? notes}) => + MeasurementEntry copyWith( + {int? id, + int? category, + DateTime? date, + num? value, + String? notes}) => MeasurementEntry( id: id ?? this.id, category: category ?? this.category, @@ -39,7 +44,8 @@ class MeasurementEntry extends Equatable { ); // Boilerplate - factory MeasurementEntry.fromJson(Map json) => _$MeasurementEntryFromJson(json); + factory MeasurementEntry.fromJson(Map json) => + _$MeasurementEntryFromJson(json); Map toJson() => _$MeasurementEntryToJson(this); diff --git a/lib/models/nutrition/ingredient.dart b/lib/models/nutrition/ingredient.dart index eb3bcf9ad..6d1a62ac4 100644 --- a/lib/models/nutrition/ingredient.dart +++ b/lib/models/nutrition/ingredient.dart @@ -65,7 +65,11 @@ class Ingredient { final num carbohydrates; /// g per 100g of product - @JsonKey(required: true, fromJson: stringToNum, toJson: numToString, name: 'carbohydrates_sugar') + @JsonKey( + required: true, + fromJson: stringToNum, + toJson: numToString, + name: 'carbohydrates_sugar') final num carbohydratesSugar; /// g per 100g of product @@ -77,7 +81,11 @@ class Ingredient { final num fat; /// g per 100g of product - @JsonKey(required: true, fromJson: stringToNum, toJson: numToString, name: 'fat_saturated') + @JsonKey( + required: true, + fromJson: stringToNum, + toJson: numToString, + name: 'fat_saturated') final num fatSaturated; /// g per 100g of product @@ -111,7 +119,8 @@ class Ingredient { }); // Boilerplate - factory Ingredient.fromJson(Map json) => _$IngredientFromJson(json); + factory Ingredient.fromJson(Map json) => + _$IngredientFromJson(json); Map toJson() => _$IngredientToJson(this); diff --git a/lib/models/nutrition/ingredient_image.dart b/lib/models/nutrition/ingredient_image.dart index 30983bfb9..9cb042b15 100644 --- a/lib/models/nutrition/ingredient_image.dart +++ b/lib/models/nutrition/ingredient_image.dart @@ -81,7 +81,8 @@ class IngredientImage { }); // Boilerplate - factory IngredientImage.fromJson(Map json) => _$IngredientImageFromJson(json); + factory IngredientImage.fromJson(Map json) => + _$IngredientImageFromJson(json); Map toJson() => _$IngredientImageToJson(this); } diff --git a/lib/models/nutrition/log.dart b/lib/models/nutrition/log.dart index ac4aa8457..00890d29d 100644 --- a/lib/models/nutrition/log.dart +++ b/lib/models/nutrition/log.dart @@ -67,7 +67,8 @@ class Log { this.comment, }); - Log.fromMealItem(MealItem mealItem, this.planId, this.mealId, [DateTime? dateTime]) { + Log.fromMealItem(MealItem mealItem, this.planId, this.mealId, + [DateTime? dateTime]) { ingredientId = mealItem.ingredientId; ingredient = mealItem.ingredient; weightUnitId = mealItem.weightUnitId; @@ -84,8 +85,9 @@ class Log { NutritionalValues get nutritionalValues { // This is already done on the server. It might be better to read it from there. - final weight = - weightUnitObj == null ? amount : amount * weightUnitObj!.amount * weightUnitObj!.grams; + final weight = weightUnitObj == null + ? amount + : amount * weightUnitObj!.amount * weightUnitObj!.grams; return ingredient.nutritionalValues / (100 / weight); } diff --git a/lib/models/nutrition/meal.dart b/lib/models/nutrition/meal.dart index ecb3ca3f5..365ead33a 100644 --- a/lib/models/nutrition/meal.dart +++ b/lib/models/nutrition/meal.dart @@ -47,8 +47,9 @@ class Meal { @JsonKey(includeFromJson: false, includeToJson: false, defaultValue: []) List diaryEntries = []; - List get diaryEntriesToday => - diaryEntries.where((element) => element.datetime.isSameDayAs(DateTime.now())).toList(); + List get diaryEntriesToday => diaryEntries + .where((element) => element.datetime.isSameDayAs(DateTime.now())) + .toList(); Meal({ this.id, @@ -70,7 +71,8 @@ class Meal { /// Calculate total nutritional value // This is already done on the server. It might be better to read it from there. NutritionalValues get plannedNutritionalValues { - return mealItems.fold(NutritionalValues(), (a, b) => a + b.nutritionalValues); + return mealItems.fold( + NutritionalValues(), (a, b) => a + b.nutritionalValues); } /// Returns the logged nutritional values for today diff --git a/lib/models/nutrition/meal_item.dart b/lib/models/nutrition/meal_item.dart index 410e43064..f89150d12 100644 --- a/lib/models/nutrition/meal_item.dart +++ b/lib/models/nutrition/meal_item.dart @@ -67,7 +67,8 @@ class MealItem { MealItem.empty(); // Boilerplate - factory MealItem.fromJson(Map json) => _$MealItemFromJson(json); + factory MealItem.fromJson(Map json) => + _$MealItemFromJson(json); Map toJson() => _$MealItemToJson(this); diff --git a/lib/models/nutrition/nutritional_goals.dart b/lib/models/nutrition/nutritional_goals.dart index 7a668a464..0489b99c4 100644 --- a/lib/models/nutrition/nutritional_goals.dart +++ b/lib/models/nutrition/nutritional_goals.dart @@ -42,22 +42,28 @@ class NutritionalGoals { // infer values where we can if (energy == null) { if (protein != null && carbohydrates != null && fat != null) { - energy = - protein! * ENERGY_PROTEIN + carbohydrates! * ENERGY_CARBOHYDRATES + fat! * ENERGY_FAT; + energy = protein! * ENERGY_PROTEIN + + carbohydrates! * ENERGY_CARBOHYDRATES + + fat! * ENERGY_FAT; } return; } // TODO: input validation when the user modifies/creates the plan, to assure energy is high enough if (protein == null && carbohydrates != null && fat != null) { - protein = - (energy! - carbohydrates! * ENERGY_CARBOHYDRATES - fat! * ENERGY_FAT) / ENERGY_PROTEIN; + protein = (energy! - + carbohydrates! * ENERGY_CARBOHYDRATES - + fat! * ENERGY_FAT) / + ENERGY_PROTEIN; assert(protein! > 0); } else if (carbohydrates == null && protein != null && fat != null) { carbohydrates = - (energy! - protein! * ENERGY_PROTEIN - fat! * ENERGY_FAT) / ENERGY_CARBOHYDRATES; + (energy! - protein! * ENERGY_PROTEIN - fat! * ENERGY_FAT) / + ENERGY_CARBOHYDRATES; assert(carbohydrates! > 0); } else if (fat == null && protein != null && carbohydrates != null) { - fat = (energy! - protein! * ENERGY_PROTEIN - carbohydrates! * ENERGY_CARBOHYDRATES) / + fat = (energy! - + protein! * ENERGY_PROTEIN - + carbohydrates! * ENERGY_CARBOHYDRATES) / ENERGY_FAT; assert(fat! > 0); } @@ -68,7 +74,8 @@ class NutritionalGoals { energy: energy != null ? energy! / v : null, protein: protein != null ? protein! / v : null, carbohydrates: carbohydrates != null ? carbohydrates! / v : null, - carbohydratesSugar: carbohydratesSugar != null ? carbohydratesSugar! / v : null, + carbohydratesSugar: + carbohydratesSugar != null ? carbohydratesSugar! / v : null, fat: fat != null ? fat! / v : null, fatSaturated: fatSaturated != null ? fatSaturated! / v : null, fiber: fiber != null ? fiber! / v : null, @@ -77,7 +84,10 @@ class NutritionalGoals { } bool isComplete() { - return energy != null && protein != null && carbohydrates != null && fat != null; + return energy != null && + protein != null && + carbohydrates != null && + fat != null; } /// Convert goals into values. @@ -110,7 +120,8 @@ class NutritionalGoals { goals.protein = (100 * protein! * ENERGY_PROTEIN) / energy!; } if (carbohydrates != null) { - goals.carbohydrates = (100 * carbohydrates! * ENERGY_CARBOHYDRATES) / energy!; + goals.carbohydrates = + (100 * carbohydrates! * ENERGY_CARBOHYDRATES) / energy!; } if (fat != null) { goals.fat = (100 * fat! * ENERGY_FAT) / energy!; diff --git a/lib/models/nutrition/nutritional_plan.dart b/lib/models/nutrition/nutritional_plan.dart index a0f678397..208ff7dc1 100644 --- a/lib/models/nutrition/nutritional_plan.dart +++ b/lib/models/nutrition/nutritional_plan.dart @@ -94,12 +94,15 @@ class NutritionalPlan { } // Boilerplate - factory NutritionalPlan.fromJson(Map json) => _$NutritionalPlanFromJson(json); + factory NutritionalPlan.fromJson(Map json) => + _$NutritionalPlanFromJson(json); Map toJson() => _$NutritionalPlanToJson(this); String getLabel(BuildContext context) { - return description != '' ? description : AppLocalizations.of(context).nutritionalPlan; + return description != '' + ? description + : AppLocalizations.of(context).nutritionalPlan; } bool get hasAnyGoals { @@ -154,7 +157,9 @@ class NutritionalPlan { final now = DateTime.now(); final today = DateTime(now.year, now.month, now.day); - return logEntriesValues.containsKey(today) ? logEntriesValues[today]! : NutritionalValues(); + return logEntriesValues.containsKey(today) + ? logEntriesValues[today]! + : NutritionalValues(); } NutritionalValues get loggedNutritionalValues7DayAvg { @@ -170,7 +175,8 @@ class NutritionalPlan { Map get logEntriesValues { final out = {}; for (final log in diaryEntries) { - final date = DateTime(log.datetime.year, log.datetime.month, log.datetime.day); + final date = + DateTime(log.datetime.year, log.datetime.month, log.datetime.day); if (!out.containsKey(date)) { out[date] = NutritionalValues(); @@ -195,7 +201,8 @@ class NutritionalPlan { final List out = []; for (final log in diaryEntries) { final dateKey = DateTime(date.year, date.month, date.day); - final logKey = DateTime(log.datetime.year, log.datetime.month, log.datetime.day); + final logKey = + DateTime(log.datetime.year, log.datetime.month, log.datetime.day); if (dateKey == logKey) { out.add(log); @@ -212,7 +219,9 @@ class NutritionalPlan { for (final meal in meals) { for (final mealItem in meal.mealItems) { final found = out.firstWhereOrNull( - (e) => e.amount == mealItem.amount && e.ingredientId == mealItem.ingredientId, + (e) => + e.amount == mealItem.amount && + e.ingredientId == mealItem.ingredientId, ); if (found == null) { diff --git a/lib/models/nutrition/weight_unit.dart b/lib/models/nutrition/weight_unit.dart index 2fab3e0af..423e39e26 100644 --- a/lib/models/nutrition/weight_unit.dart +++ b/lib/models/nutrition/weight_unit.dart @@ -31,6 +31,7 @@ class WeightUnit { const WeightUnit({required this.id, required this.name}); // Boilerplate - factory WeightUnit.fromJson(Map json) => _$WeightUnitFromJson(json); + factory WeightUnit.fromJson(Map json) => + _$WeightUnitFromJson(json); Map toJson() => _$WeightUnitToJson(this); } diff --git a/lib/models/user/profile.dart b/lib/models/user/profile.dart index ed7cb174a..b1fc7a294 100644 --- a/lib/models/user/profile.dart +++ b/lib/models/user/profile.dart @@ -48,7 +48,8 @@ class Profile { }); // Boilerplate - factory Profile.fromJson(Map json) => _$ProfileFromJson(json); + factory Profile.fromJson(Map json) => + _$ProfileFromJson(json); Map toJson() => _$ProfileToJson(this); } diff --git a/lib/models/workouts/day.dart b/lib/models/workouts/day.dart index 88b5954c4..625308ca3 100644 --- a/lib/models/workouts/day.dart +++ b/lib/models/workouts/day.dart @@ -75,7 +75,8 @@ class Day { final now = DateTime.now(); final firstDayOfWeek = now.subtract(Duration(days: now.weekday)); - return DateFormat(DateFormat.WEEKDAY, locale).format(firstDayOfWeek.add(Duration(days: day))); + return DateFormat(DateFormat.WEEKDAY, locale) + .format(firstDayOfWeek.add(Duration(days: day))); } // Boilerplate diff --git a/lib/models/workouts/log.dart b/lib/models/workouts/log.dart index 17cbd7e1c..728285223 100644 --- a/lib/models/workouts/log.dart +++ b/lib/models/workouts/log.dart @@ -111,7 +111,8 @@ class Log { /// Returns the text representation for a single setting, used in the gym mode String get singleLogRepTextNoNl { - return repText(reps, repetitionUnitObj, weight, weightUnitObj, rir).replaceAll('\n', ''); + return repText(reps, repetitionUnitObj, weight, weightUnitObj, rir) + .replaceAll('\n', ''); } /// Override the equals operator @@ -132,8 +133,8 @@ class Log { @override //ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => - Object.hash(exerciseBaseId, weight, weightUnitId, reps, repetitionUnitId, rir); + int get hashCode => Object.hash( + exerciseBaseId, weight, weightUnitId, reps, repetitionUnitId, rir); //@override //int get hashCode => super.hashCode; diff --git a/lib/models/workouts/repetition_unit.dart b/lib/models/workouts/repetition_unit.dart index 207b69b1f..64e38bf99 100644 --- a/lib/models/workouts/repetition_unit.dart +++ b/lib/models/workouts/repetition_unit.dart @@ -31,6 +31,7 @@ class RepetitionUnit { const RepetitionUnit({required this.id, required this.name}); // Boilerplate - factory RepetitionUnit.fromJson(Map json) => _$RepetitionUnitFromJson(json); + factory RepetitionUnit.fromJson(Map json) => + _$RepetitionUnitFromJson(json); Map toJson() => _$RepetitionUnitToJson(this); } diff --git a/lib/models/workouts/session.dart b/lib/models/workouts/session.dart index 1c2aea7bf..27aee13f2 100644 --- a/lib/models/workouts/session.dart +++ b/lib/models/workouts/session.dart @@ -41,10 +41,18 @@ class WorkoutSession { @JsonKey(required: false, defaultValue: '') late String notes; - @JsonKey(required: true, name: 'time_start', toJson: timeToString, fromJson: stringToTime) + @JsonKey( + required: true, + name: 'time_start', + toJson: timeToString, + fromJson: stringToTime) late TimeOfDay timeStart; - @JsonKey(required: true, name: 'time_end', toJson: timeToString, fromJson: stringToTime) + @JsonKey( + required: true, + name: 'time_end', + toJson: timeToString, + fromJson: stringToTime) late TimeOfDay timeEnd; WorkoutSession(); @@ -65,7 +73,8 @@ class WorkoutSession { } // Boilerplate - factory WorkoutSession.fromJson(Map json) => _$WorkoutSessionFromJson(json); + factory WorkoutSession.fromJson(Map json) => + _$WorkoutSessionFromJson(json); Map toJson() => _$WorkoutSessionToJson(this); String? get impressionAsString { diff --git a/lib/models/workouts/set.dart b/lib/models/workouts/set.dart index a1caa104d..f4a373b8c 100644 --- a/lib/models/workouts/set.dart +++ b/lib/models/workouts/set.dart @@ -110,7 +110,9 @@ class Set { /// Returns all settings for the given exercise List filterSettingsByExercise(Exercise exerciseBase) { - return settings.where((element) => element.exerciseId == exerciseBase.id).toList(); + return settings + .where((element) => element.exerciseId == exerciseBase.id) + .toList(); } /// Returns a list with all repetitions for the given exercise diff --git a/lib/models/workouts/setting.dart b/lib/models/workouts/setting.dart index 035e431f0..184f16d75 100644 --- a/lib/models/workouts/setting.dart +++ b/lib/models/workouts/setting.dart @@ -29,7 +29,18 @@ part 'setting.g.dart'; class Setting { /// Allowed RiR values. This list must be kept in sync with RIR_OPTIONS in the /// wger server - static const POSSIBLE_RIR_VALUES = ['', '0', '0.5', '1', '1.5', '2', '2.5', '3', '3.5', '4']; + static const POSSIBLE_RIR_VALUES = [ + '', + '0', + '0.5', + '1', + '1.5', + '2', + '2.5', + '3', + '3.5', + '4' + ]; static const DEFAULT_RIR = ''; @JsonKey(required: true) @@ -88,7 +99,8 @@ class Setting { Setting.empty(); // Boilerplate - factory Setting.fromJson(Map json) => _$SettingFromJson(json); + factory Setting.fromJson(Map json) => + _$SettingFromJson(json); Map toJson() => _$SettingToJson(this); diff --git a/lib/models/workouts/weight_unit.dart b/lib/models/workouts/weight_unit.dart index 2fab3e0af..423e39e26 100644 --- a/lib/models/workouts/weight_unit.dart +++ b/lib/models/workouts/weight_unit.dart @@ -31,6 +31,7 @@ class WeightUnit { const WeightUnit({required this.id, required this.name}); // Boilerplate - factory WeightUnit.fromJson(Map json) => _$WeightUnitFromJson(json); + factory WeightUnit.fromJson(Map json) => + _$WeightUnitFromJson(json); Map toJson() => _$WeightUnitToJson(this); } diff --git a/lib/models/workouts/workout_plan.dart b/lib/models/workouts/workout_plan.dart index 995bd9c59..d6d22d5ef 100644 --- a/lib/models/workouts/workout_plan.dart +++ b/lib/models/workouts/workout_plan.dart @@ -63,7 +63,8 @@ class WorkoutPlan { } // Boilerplate - factory WorkoutPlan.fromJson(Map json) => _$WorkoutPlanFromJson(json); + factory WorkoutPlan.fromJson(Map json) => + _$WorkoutPlanFromJson(json); Map toJson() => _$WorkoutPlanToJson(this); @@ -73,8 +74,11 @@ class WorkoutPlan { /// means here that the values are the same, i.e. logs with the same weight, /// reps, etc. are considered equal. Workout ID, Log ID and date are not /// considered. - List filterLogsByExerciseBase(Exercise exerciseBase, {bool unique = false}) { - var out = logs.where((element) => element.exerciseBaseId == exerciseBase.id).toList(); + List filterLogsByExerciseBase(Exercise exerciseBase, + {bool unique = false}) { + var out = logs + .where((element) => element.exerciseBaseId == exerciseBase.id) + .toList(); if (unique) { out = out.toSet().toList(); diff --git a/lib/providers/add_exercise.dart b/lib/providers/add_exercise.dart index 718e149e5..7d3db78e5 100644 --- a/lib/providers/add_exercise.dart +++ b/lib/providers/add_exercise.dart @@ -65,11 +65,13 @@ class AddExerciseProvider with ChangeNotifier { set descriptionEn(String description) => _descriptionEn = description; - set descriptionTrans(String description) => _descriptionTranslation = description; + set descriptionTrans(String description) => + _descriptionTranslation = description; set alternateNamesEn(List names) => _alternativeNamesEn = names; - set alternateNamesTrans(List names) => _alternativeNamesTranslation = names; + set alternateNamesTrans(List names) => + _alternativeNamesTranslation = names; set equipment(List equipment) => _equipment = equipment; @@ -107,7 +109,8 @@ class AddExerciseProvider with ChangeNotifier { return Translation( name: _nameEn!, description: _descriptionEn!, - language: const Language(id: 2, fullName: 'English', shortName: 'en'), + languageObj: const Language(id: 2, fullName: 'English', shortName: 'en'), + languageId: 2, ); } @@ -115,7 +118,8 @@ class AddExerciseProvider with ChangeNotifier { return Translation( name: _nameTranslation!, description: _descriptionTranslation!, - language: language, + languageObj: language, + languageId: language!.id, ); } @@ -181,19 +185,23 @@ class AddExerciseProvider with ChangeNotifier { // Create the base description in English Translation exerciseTranslationEn = translationEn; - exerciseTranslationEn.exercise = exercise; + exerciseTranslationEn = + exerciseTranslationEn.copyWith(exerciseId: exercise.id); exerciseTranslationEn = await addExerciseTranslation(exerciseTranslationEn); for (final alias in _alternativeNamesEn) { if (alias.isNotEmpty) { - exerciseTranslationEn.aliases.add(await addExerciseAlias(alias, exerciseTranslationEn.id!)); + exerciseTranslationEn.aliases + .add(await addExerciseAlias(alias, exerciseTranslationEn.id!)); } } // Create the translations if (language != null) { Translation exerciseTranslationLang = translation; - exerciseTranslationLang.exercise = exercise; - exerciseTranslationLang = await addExerciseTranslation(exerciseTranslationLang); + exerciseTranslationLang = + exerciseTranslationLang.copyWith(exerciseId: exercise.id); + exerciseTranslationLang = + await addExerciseTranslation(exerciseTranslationLang); for (final alias in _alternativeNamesTranslation) { if (alias.isNotEmpty) { exerciseTranslationLang.aliases.add( @@ -217,7 +225,8 @@ class AddExerciseProvider with ChangeNotifier { Future addExerciseBase() async { final Uri postUri = baseProvider.makeUrl(_exerciseBaseUrlPath); - final Map newBaseMap = await baseProvider.post(exercise.toJson(), postUri); + final Map newBaseMap = + await baseProvider.post(exercise.toJson(), postUri); final Exercise newExerciseBase = Exercise.fromJson(newBaseMap); notifyListeners(); @@ -228,7 +237,8 @@ class AddExerciseProvider with ChangeNotifier { final Uri postUri = baseProvider.makeUrl(_exerciseVariationPath); // We send an empty dictionary since at the moment the variations only have an ID - final Map variationMap = await baseProvider.post({}, postUri); + final Map variationMap = + await baseProvider.post({}, postUri); final Variation newVariation = Variation.fromJson(variationMap); _variationId = newVariation.id; notifyListeners(); @@ -237,7 +247,8 @@ class AddExerciseProvider with ChangeNotifier { Future addImages(Exercise base) async { for (final image in _exerciseImages) { - final request = http.MultipartRequest('POST', baseProvider.makeUrl(_imagesUrlPath)); + final request = + http.MultipartRequest('POST', baseProvider.makeUrl(_imagesUrlPath)); request.headers.addAll(baseProvider.getDefaultHeaders(includeAuth: true)); request.files.add(await http.MultipartFile.fromPath('image', image.path)); @@ -253,7 +264,8 @@ class AddExerciseProvider with ChangeNotifier { Future addExerciseTranslation(Translation exercise) async { final Uri postUri = baseProvider.makeUrl(_exerciseTranslationUrlPath); - final Map newTranslation = await baseProvider.post(exercise.toJson(), postUri); + final Map newTranslation = + await baseProvider.post(exercise.toJson(), postUri); final Translation newExercise = Translation.fromJson(newTranslation); notifyListeners(); @@ -264,7 +276,8 @@ class AddExerciseProvider with ChangeNotifier { final alias = Alias(exerciseId: exerciseId, alias: name); final Uri postUri = baseProvider.makeUrl(_exerciseAliasPath); - final Alias newAlias = Alias.fromJson(await baseProvider.post(alias.toJson(), postUri)); + final Alias newAlias = + Alias.fromJson(await baseProvider.post(alias.toJson(), postUri)); notifyListeners(); return newAlias; diff --git a/lib/providers/auth.dart b/lib/providers/auth.dart index 1bfbdca12..0e92faaf8 100644 --- a/lib/providers/auth.dart +++ b/lib/providers/auth.dart @@ -51,7 +51,7 @@ class AuthProvider with ChangeNotifier { late http.Client client; - AuthProvider([http.Client? client, bool? checkMetadata]) { + AuthProvider([http.Client? client]) { this.client = client ?? http.Client(); } diff --git a/lib/providers/base_provider.dart b/lib/providers/base_provider.dart index e729e8cd1..f81f09a34 100644 --- a/lib/providers/base_provider.dart +++ b/lib/providers/base_provider.dart @@ -51,7 +51,8 @@ class WgerBaseProvider { } /// Helper function to make a URL. - Uri makeUrl(String path, {int? id, String? objectMethod, Map? query}) { + Uri makeUrl(String path, + {int? id, String? objectMethod, Map? query}) { return makeUri(auth.serverUrl!, path, id, objectMethod, query); } diff --git a/lib/providers/body_weight.dart b/lib/providers/body_weight.dart index 4ecba70b0..b4528cb17 100644 --- a/lib/providers/body_weight.dart +++ b/lib/providers/body_weight.dart @@ -77,7 +77,8 @@ class BodyWeightProvider with ChangeNotifier { Future addEntry(WeightEntry entry) async { // Create entry and return it - final data = await baseProvider.post(entry.toJson(), baseProvider.makeUrl(BODY_WEIGHT_URL)); + final data = await baseProvider.post( + entry.toJson(), baseProvider.makeUrl(BODY_WEIGHT_URL)); final WeightEntry weightEntry = WeightEntry.fromJson(data); _entries.add(weightEntry); _entries.sort((a, b) => b.date.compareTo(a.date)); @@ -96,7 +97,8 @@ class BodyWeightProvider with ChangeNotifier { Future deleteEntry(int id) async { // Send the request and remove the entry from the list... - final existingEntryIndex = _entries.indexWhere((element) => element.id == id); + final existingEntryIndex = + _entries.indexWhere((element) => element.id == id); final existingWeightEntry = _entries[existingEntryIndex]; _entries.removeAt(existingEntryIndex); notifyListeners(); diff --git a/lib/providers/exercises.dart b/lib/providers/exercises.dart index dc13c8235..f5b4d168f 100644 --- a/lib/providers/exercises.dart +++ b/lib/providers/exercises.dart @@ -21,7 +21,7 @@ import 'dart:convert'; import 'dart:developer'; import 'package:drift/drift.dart'; -import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:wger/core/locator.dart'; import 'package:wger/database/exercises/exercise_database.dart'; @@ -126,7 +126,8 @@ class ExercisesProvider with ChangeNotifier { title: 'Equipment', items: Map.fromEntries( _equipment.map( - (singleEquipment) => MapEntry(singleEquipment, false), + (singleEquipment) => + MapEntry(singleEquipment, false), ), ), ), @@ -156,13 +157,15 @@ class ExercisesProvider with ChangeNotifier { // Filter by exercise category and equipment (REPLACE WITH HTTP REQUEST) filteredExercises = filteredItems.where((exercise) { - final bool isInAnyCategory = filters!.exerciseCategories.selected.contains(exercise.category); + final bool isInAnyCategory = + filters!.exerciseCategories.selected.contains(exercise.category); final bool doesContainAnyEquipment = filters!.equipment.selected.any( (selectedEquipment) => exercise.equipment.contains(selectedEquipment), ); - return (isInAnyCategory || filters!.exerciseCategories.selected.isEmpty) && + return (isInAnyCategory || + filters!.exerciseCategories.selected.isEmpty) && (doesContainAnyEquipment || filters!.equipment.selected.isEmpty); }).toList(); } @@ -237,14 +240,16 @@ class ExercisesProvider with ChangeNotifier { } Future fetchAndSetCategoriesFromApi() async { - final categories = await baseProvider.fetchPaginated(baseProvider.makeUrl(categoriesUrlPath)); + final categories = await baseProvider + .fetchPaginated(baseProvider.makeUrl(categoriesUrlPath)); for (final category in categories) { _categories.add(ExerciseCategory.fromJson(category)); } } Future fetchAndSetMusclesFromApi() async { - final muscles = await baseProvider.fetchPaginated(baseProvider.makeUrl(musclesUrlPath)); + final muscles = + await baseProvider.fetchPaginated(baseProvider.makeUrl(musclesUrlPath)); for (final muscle in muscles) { _muscles.add(Muscle.fromJson(muscle)); @@ -252,7 +257,8 @@ class ExercisesProvider with ChangeNotifier { } Future fetchAndSetEquipmentsFromApi() async { - final equipments = await baseProvider.fetchPaginated(baseProvider.makeUrl(equipmentUrlPath)); + final equipments = await baseProvider + .fetchPaginated(baseProvider.makeUrl(equipmentUrlPath)); for (final equipment in equipments) { _equipment.add(Equipment.fromJson(equipment)); @@ -260,7 +266,8 @@ class ExercisesProvider with ChangeNotifier { } Future fetchAndSetLanguagesFromApi() async { - final languageData = await baseProvider.fetchPaginated(baseProvider.makeUrl(languageUrlPath)); + final languageData = await baseProvider + .fetchPaginated(baseProvider.makeUrl(languageUrlPath)); for (final language in languageData) { _languages.add(Language.fromJson(language)); @@ -304,7 +311,8 @@ class ExercisesProvider with ChangeNotifier { // Exercise is already known locally if (exerciseDb != null) { - final nextFetch = exerciseDb.lastFetched.add(const Duration(hours: EXERCISE_FETCH_HOURS)); + final nextFetch = exerciseDb.lastFetched + .add(const Duration(hours: EXERCISE_FETCH_HOURS)); exercise = Exercise.fromApiDataString(exerciseDb.data, _languages); // Fetch and update @@ -318,7 +326,9 @@ class ExercisesProvider with ChangeNotifier { if (exerciseApiData.lastUpdateGlobal.isAfter(exerciseDb.lastUpdate)) { exercise = Exercise.fromApiData(exerciseApiData, _languages); - await (database.update(database.exercises)..where((e) => e.id.equals(exerciseId))).write( + await (database.update(database.exercises) + ..where((e) => e.id.equals(exerciseId))) + .write( ExercisesCompanion( data: Value(jsonEncode(apiData)), lastUpdate: Value(exercise.lastUpdateGlobal!), @@ -327,7 +337,9 @@ class ExercisesProvider with ChangeNotifier { ); // Update last fetched date, otherwise we'll keep hitting the API } else { - await (database.update(database.exercises)..where((e) => e.id.equals(exerciseId))).write( + await (database.update(database.exercises) + ..where((e) => e.id.equals(exerciseId))) + .write( ExercisesCompanion(lastFetched: Value(DateTime.now())), ); } @@ -423,7 +435,9 @@ class ExercisesProvider with ChangeNotifier { final exercisesDb = await database.select(database.exercises).get(); log('Loaded ${exercisesDb.length} exercises from cache'); - exercises = exercisesDb.map((e) => Exercise.fromApiDataString(e.data, _languages)).toList(); + exercises = exercisesDb + .map((e) => Exercise.fromApiDataString(e.data, _languages)) + .toList(); } /// Updates the exercise database with *all* the exercises from the server @@ -433,7 +447,9 @@ class ExercisesProvider with ChangeNotifier { ); final List exercisesData = data['results']; - exercises = exercisesData.map((e) => Exercise.fromApiDataJson(e, _languages)).toList(); + exercises = exercisesData + .map((e) => Exercise.fromApiDataJson(e, _languages)) + .toList(); // Insert new entries and update ones that have been edited Future.forEach(exercisesData, (exerciseData) async { @@ -457,14 +473,19 @@ class ExercisesProvider with ChangeNotifier { final lastUpdateApi = DateTime.parse(exerciseData['last_update_global']); if (exercise != null && lastUpdateApi.isAfter(exercise.lastUpdate)) { // TODO: timezones 🥳 - print( - 'Exercise ${exercise.id}: update API $lastUpdateApi | Update DB: ${exercise.lastUpdate}', - ); - (database.update(database.exercises)..where((e) => e.id.equals(exerciseData['id']))).write( + if (kDebugMode) { + print( + 'Exercise ${exercise.id}: update API $lastUpdateApi | Update DB: ${exercise.lastUpdate}', + ); + } + (database.update(database.exercises) + ..where((e) => e.id.equals(exerciseData['id']))) + .write( ExercisesCompanion( id: Value(exerciseData['id']), data: Value(jsonEncode(exerciseData)), - lastUpdate: Value(DateTime.parse(exerciseData['last_update_global'])), + lastUpdate: + Value(DateTime.parse(exerciseData['last_update_global'])), lastFetched: Value(DateTime.now()), ), ); @@ -477,7 +498,8 @@ class ExercisesProvider with ChangeNotifier { /// We first try to read from the local DB, and from the API if the data is too old Future fetchAndSetMuscles(ExerciseDatabase database) async { final prefs = await SharedPreferences.getInstance(); - var validTill = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_MUSCLES)!); + var validTill = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_MUSCLES)!); // Cache still valid, return it if (validTill.isAfter(DateTime.now())) { @@ -511,7 +533,8 @@ class ExercisesProvider with ChangeNotifier { /// We first try to read from the local DB, and from the API if the data is too old Future fetchAndSetCategories(ExerciseDatabase database) async { final prefs = await SharedPreferences.getInstance(); - var validTill = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_CATEGORIES)!); + var validTill = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_CATEGORIES)!); // Cache still valid, return it if (validTill.isAfter(DateTime.now())) { @@ -544,7 +567,8 @@ class ExercisesProvider with ChangeNotifier { /// We first try to read from the local DB, and from the API if the data is too old Future fetchAndSetLanguages(ExerciseDatabase database) async { final prefs = await SharedPreferences.getInstance(); - var validTill = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_LANGUAGES)!); + var validTill = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_LANGUAGES)!); // Cache still valid, return it if (validTill.isAfter(DateTime.now())) { @@ -576,7 +600,8 @@ class ExercisesProvider with ChangeNotifier { /// We first try to read from the local DB, and from the API if the data is too old Future fetchAndSetEquipments(ExerciseDatabase database) async { final prefs = await SharedPreferences.getInstance(); - var validTill = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_EQUIPMENT)!); + var validTill = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_EQUIPMENT)!); // Cache still valid, return it if (validTill.isAfter(DateTime.now())) { @@ -679,8 +704,10 @@ class Filters { List get filterCategories => [exerciseCategories, equipment]; bool get isNothingMarked { - final isExerciseCategoryMarked = exerciseCategories.items.values.any((isMarked) => isMarked); - final isEquipmentMarked = equipment.items.values.any((isMarked) => isMarked); + final isExerciseCategoryMarked = + exerciseCategories.items.values.any((isMarked) => isMarked); + final isEquipmentMarked = + equipment.items.values.any((isMarked) => isMarked); return !isExerciseCategoryMarked && !isEquipmentMarked; } diff --git a/lib/providers/gallery.dart b/lib/providers/gallery.dart index f55a81191..e9ac92579 100644 --- a/lib/providers/gallery.dart +++ b/lib/providers/gallery.dart @@ -31,7 +31,8 @@ class GalleryProvider extends WgerBaseProvider with ChangeNotifier { List images = []; - GalleryProvider(super.auth, List entries, [super.client]) : images = entries; + GalleryProvider(super.auth, List entries, [super.client]) + : images = entries; /// Clears all lists void clear() { @@ -60,7 +61,8 @@ class GalleryProvider extends WgerBaseProvider with ChangeNotifier { HttpHeaders.authorizationHeader: 'Token ${auth.token}', HttpHeaders.userAgentHeader: auth.getAppNameHeader(), }); - request.files.add(await http.MultipartFile.fromPath('image', imageFile.path)); + request.files + .add(await http.MultipartFile.fromPath('image', imageFile.path)); request.fields['date'] = toDate(image.date)!; request.fields['description'] = image.description; @@ -74,7 +76,8 @@ class GalleryProvider extends WgerBaseProvider with ChangeNotifier { } Future editImage(gallery.Image image, XFile? imageFile) async { - final request = http.MultipartRequest('PATCH', makeUrl(_galleryUrlPath, id: image.id)); + final request = + http.MultipartRequest('PATCH', makeUrl(_galleryUrlPath, id: image.id)); request.headers.addAll({ HttpHeaders.authorizationHeader: 'Token ${auth.token}', HttpHeaders.userAgentHeader: auth.getAppNameHeader(), @@ -82,7 +85,8 @@ class GalleryProvider extends WgerBaseProvider with ChangeNotifier { // Only send the image if a new one was selected if (imageFile != null) { - request.files.add(await http.MultipartFile.fromPath('image', imageFile.path)); + request.files + .add(await http.MultipartFile.fromPath('image', imageFile.path)); } // Update image info @@ -100,7 +104,7 @@ class GalleryProvider extends WgerBaseProvider with ChangeNotifier { } Future deleteImage(gallery.Image image) async { - final response = await deleteRequest(_galleryUrlPath, image.id!); + await deleteRequest(_galleryUrlPath, image.id!); images.removeWhere((element) => element.id == image.id); notifyListeners(); diff --git a/lib/providers/measurement.dart b/lib/providers/measurement.dart index de9d9bcf5..0f01039ef 100644 --- a/lib/providers/measurement.dart +++ b/lib/providers/measurement.dart @@ -68,13 +68,15 @@ class MeasurementProvider with ChangeNotifier { final categoryIndex = _categories.indexOf(category); // Process the response - final requestUrl = baseProvider.makeUrl(_entryUrl, query: {'category': category.id.toString()}); + final requestUrl = baseProvider + .makeUrl(_entryUrl, query: {'category': category.id.toString()}); final data = await baseProvider.fetch(requestUrl); final List loadedEntries = []; for (final entry in data['results']) { loadedEntries.add(MeasurementEntry.fromJson(entry)); } - final MeasurementCategory editedCategory = category.copyWith(entries: loadedEntries); + final MeasurementCategory editedCategory = + category.copyWith(entries: loadedEntries); _categories.removeAt(categoryIndex); _categories.insert(categoryIndex, editedCategory); notifyListeners(); @@ -83,15 +85,18 @@ class MeasurementProvider with ChangeNotifier { /// Fetches and sets the measurement categories and their entries Future fetchAndSetAllCategoriesAndEntries() async { await fetchAndSetCategories(); - await Future.wait(_categories.map((e) => fetchAndSetCategoryEntries(e.id!)).toList()); + await Future.wait( + _categories.map((e) => fetchAndSetCategoryEntries(e.id!)).toList()); } /// Adds a measurement category Future addCategory(MeasurementCategory category) async { final Uri postUri = baseProvider.makeUrl(_categoryUrl); - final Map newCategoryMap = await baseProvider.post(category.toJson(), postUri); - final MeasurementCategory newCategory = MeasurementCategory.fromJson(newCategoryMap); + final Map newCategoryMap = + await baseProvider.post(category.toJson(), postUri); + final MeasurementCategory newCategory = + MeasurementCategory.fromJson(newCategoryMap); _categories.add(newCategory); _categories.sort((a, b) => a.name.compareTo(b.name)); notifyListeners(); @@ -118,14 +123,16 @@ class MeasurementProvider with ChangeNotifier { Future editCategory(int id, String? newName, String? newUnit) async { final MeasurementCategory oldCategory = findCategoryById(id); final int categoryIndex = _categories.indexOf(oldCategory); - final MeasurementCategory tempNewCategory = oldCategory.copyWith(name: newName, unit: newUnit); + final MeasurementCategory tempNewCategory = + oldCategory.copyWith(name: newName, unit: newUnit); final Map response = await baseProvider.patch( tempNewCategory.toJson(), baseProvider.makeUrl(_categoryUrl, id: id), ); final MeasurementCategory newCategory = - MeasurementCategory.fromJson(response).copyWith(entries: oldCategory.entries); + MeasurementCategory.fromJson(response) + .copyWith(entries: oldCategory.entries); _categories.removeAt(categoryIndex); _categories.insert(categoryIndex, newCategory); notifyListeners(); @@ -135,7 +142,8 @@ class MeasurementProvider with ChangeNotifier { Future addEntry(MeasurementEntry entry) async { final Uri postUri = baseProvider.makeUrl(_entryUrl); - final Map newEntryMap = await baseProvider.post(entry.toJson(), postUri); + final Map newEntryMap = + await baseProvider.post(entry.toJson(), postUri); final MeasurementEntry newEntry = MeasurementEntry.fromJson(newEntryMap); final MeasurementCategory category = findCategoryById(newEntry.category); @@ -183,8 +191,8 @@ class MeasurementProvider with ChangeNotifier { date: newDate, ); - final Map response = - await baseProvider.patch(tempNewEntry.toJson(), baseProvider.makeUrl(_entryUrl, id: id)); + final Map response = await baseProvider.patch( + tempNewEntry.toJson(), baseProvider.makeUrl(_entryUrl, id: id)); final MeasurementEntry newEntry = MeasurementEntry.fromJson(response); category.entries.removeAt(entryIndex); diff --git a/lib/providers/nutrition.dart b/lib/providers/nutrition.dart index d1a17de8b..c7e492cac 100644 --- a/lib/providers/nutrition.dart +++ b/lib/providers/nutrition.dart @@ -107,7 +107,8 @@ class NutritionPlansProvider with ChangeNotifier { /// Fetches and sets all plans fully, i.e. with all corresponding child objects Future fetchAndSetAllPlansFull() async { - final data = await baseProvider.fetchPaginated(baseProvider.makeUrl(_nutritionalPlansPath)); + final data = await baseProvider + .fetchPaginated(baseProvider.makeUrl(_nutritionalPlansPath)); await Future.wait(data.map((e) => fetchAndSetPlanFull(e['id'])).toList()); } @@ -166,7 +167,8 @@ class NutritionPlansProvider with ChangeNotifier { // Logs await fetchAndSetLogs(plan); for (final meal in meals) { - meal.diaryEntries = plan.diaryEntries.where((e) => e.mealId == meal.id).toList(); + meal.diaryEntries = + plan.diaryEntries.where((e) => e.mealId == meal.id).toList(); } // ... and done @@ -200,7 +202,8 @@ class NutritionPlansProvider with ChangeNotifier { _plans.removeAt(existingPlanIndex); notifyListeners(); - final response = await baseProvider.deleteRequest(_nutritionalPlansPath, id); + final response = + await baseProvider.deleteRequest(_nutritionalPlansPath, id); if (response.statusCode >= 400) { _plans.insert(existingPlanIndex, existingPlan); @@ -280,7 +283,8 @@ class NutritionPlansProvider with ChangeNotifier { notifyListeners(); // Try to delete - final response = await baseProvider.deleteRequest(_mealItemPath, mealItem.id!); + final response = + await baseProvider.deleteRequest(_mealItemPath, mealItem.id!); if (response.statusCode >= 400) { meal.mealItems.insert(mealItemIndex, existingMealItem); notifyListeners(); @@ -295,7 +299,8 @@ class NutritionPlansProvider with ChangeNotifier { /// Fetch and return an ingredient /// /// If the ingredient is not known locally, it is fetched from the server - Future fetchIngredient(int ingredientId, {IngredientDatabase? database}) async { + Future fetchIngredient(int ingredientId, + {IngredientDatabase? database}) async { database ??= this.database; Ingredient ingredient; @@ -313,9 +318,11 @@ class NutritionPlansProvider with ChangeNotifier { log("Loaded ingredient '${ingredient.name}' from db cache"); // Prune old entries - if (DateTime.now() - .isAfter(ingredientDb.lastFetched.add(const Duration(days: DAYS_TO_CACHE)))) { - (database.delete(database.ingredients)..where((i) => i.id.equals(ingredientId))).go(); + if (DateTime.now().isAfter(ingredientDb.lastFetched + .add(const Duration(days: DAYS_TO_CACHE)))) { + (database.delete(database.ingredients) + ..where((i) => i.id.equals(ingredientId))) + .go(); } } else { final data = await baseProvider.fetch( @@ -343,7 +350,9 @@ class NutritionPlansProvider with ChangeNotifier { final ingredientDb = await database.select(database.ingredients).get(); log('Read ${ingredientDb.length} ingredients from db cache'); if (ingredientDb.isNotEmpty) { - ingredients = ingredientDb.map((e) => Ingredient.fromJson(jsonDecode(e.data))).toList(); + ingredients = ingredientDb + .map((e) => Ingredient.fromJson(jsonDecode(e.data))) + .toList(); } } diff --git a/lib/providers/user.dart b/lib/providers/user.dart index cb547c49d..a703f007f 100644 --- a/lib/providers/user.dart +++ b/lib/providers/user.dart @@ -38,7 +38,8 @@ class UserProvider with ChangeNotifier { /// Fetch the current user's profile Future fetchAndSetProfile() async { - final userData = await baseProvider.fetch(baseProvider.makeUrl(PROFILE_URL)); + final userData = + await baseProvider.fetch(baseProvider.makeUrl(PROFILE_URL)); try { profile = Profile.fromJson(userData); } catch (error) { @@ -48,7 +49,7 @@ class UserProvider with ChangeNotifier { /// Save the user's profile to the server Future saveProfile() async { - final data = await baseProvider.post( + await baseProvider.post( profile!.toJson(), baseProvider.makeUrl(PROFILE_URL), ); @@ -56,7 +57,7 @@ class UserProvider with ChangeNotifier { /// Verify the user's email Future verifyEmail() async { - final verificationData = await baseProvider.fetch(baseProvider.makeUrl( + await baseProvider.fetch(baseProvider.makeUrl( PROFILE_URL, objectMethod: VERIFY_EMAIL, )); diff --git a/lib/providers/workout_plans.dart b/lib/providers/workout_plans.dart index 04aab0bc6..51de6ba77 100644 --- a/lib/providers/workout_plans.dart +++ b/lib/providers/workout_plans.dart @@ -78,7 +78,8 @@ class WorkoutPlansProvider with ChangeNotifier { /// Return the default weight unit (kg) WeightUnit get defaultWeightUnit { - return _weightUnits.firstWhere((element) => element.id == DEFAULT_WEIGHT_UNIT); + return _weightUnits + .firstWhere((element) => element.id == DEFAULT_WEIGHT_UNIT); } List get repetitionUnits { @@ -87,7 +88,8 @@ class WorkoutPlansProvider with ChangeNotifier { /// Return the default weight unit (reps) RepetitionUnit get defaultRepetitionUnit { - return _repetitionUnit.firstWhere((element) => element.id == REP_UNIT_REPETITIONS); + return _repetitionUnit + .firstWhere((element) => element.id == REP_UNIT_REPETITIONS); } List getPlans() { @@ -195,7 +197,8 @@ class WorkoutPlansProvider with ChangeNotifier { // Days final List days = []; final daysData = await baseProvider.fetch( - baseProvider.makeUrl(_daysUrlPath, query: {'training': plan.id.toString()}), + baseProvider + .makeUrl(_daysUrlPath, query: {'training': plan.id.toString()}), ); for (final dayEntry in daysData['results']) { final day = Day.fromJson(dayEntry); @@ -203,7 +206,8 @@ class WorkoutPlansProvider with ChangeNotifier { // Sets final List sets = []; final setData = await baseProvider.fetch( - baseProvider.makeUrl(_setsUrlPath, query: {'exerciseday': day.id.toString()}), + baseProvider + .makeUrl(_setsUrlPath, query: {'exerciseday': day.id.toString()}), ); for (final setEntry in setData['results']) { final workoutSet = Set.fromJson(setEntry); @@ -211,19 +215,22 @@ class WorkoutPlansProvider with ChangeNotifier { fetchComputedSettings(workoutSet); // request! final List settings = []; - final settingData = allSettingsData['results'].where((s) => s['set'] == workoutSet.id); + final settingData = + allSettingsData['results'].where((s) => s['set'] == workoutSet.id); for (final settingEntry in settingData) { final workoutSetting = Setting.fromJson(settingEntry); - workoutSetting.exercise = await _exercises.fetchAndSetExercise(workoutSetting.exerciseId); + workoutSetting.exercise = + await _exercises.fetchAndSetExercise(workoutSetting.exerciseId); workoutSetting.weightUnit = _weightUnits.firstWhere( (e) => e.id == workoutSetting.weightUnitId, ); workoutSetting.repetitionUnit = _repetitionUnit.firstWhere( (e) => e.id == workoutSetting.repetitionUnitId, ); - if (!workoutSet.exerciseBasesIds.contains(workoutSetting.exerciseId)) { + if (!workoutSet.exerciseBasesIds + .contains(workoutSetting.exerciseId)) { workoutSet.addExerciseBase(workoutSetting.exerciseObj); } @@ -247,9 +254,12 @@ class WorkoutPlansProvider with ChangeNotifier { for (final logEntry in logData) { try { final log = Log.fromJson(logEntry); - log.weightUnit = _weightUnits.firstWhere((e) => e.id == log.weightUnitId); - log.repetitionUnit = _repetitionUnit.firstWhere((e) => e.id == log.weightUnitId); - log.exerciseBase = await _exercises.fetchAndSetExercise(log.exerciseBaseId); + log.weightUnit = + _weightUnits.firstWhere((e) => e.id == log.weightUnitId); + log.repetitionUnit = + _repetitionUnit.firstWhere((e) => e.id == log.weightUnitId); + log.exerciseBase = + await _exercises.fetchAndSetExercise(log.exerciseBaseId); plan.logs.add(log); } catch (e) { dev.log('fire! fire!'); @@ -282,7 +292,8 @@ class WorkoutPlansProvider with ChangeNotifier { } Future deleteWorkout(int id) async { - final existingWorkoutIndex = _workoutPlans.indexWhere((element) => element.id == id); + final existingWorkoutIndex = + _workoutPlans.indexWhere((element) => element.id == id); final existingWorkout = _workoutPlans[existingWorkoutIndex]; _workoutPlans.removeAt(existingWorkoutIndex); notifyListeners(); @@ -313,8 +324,8 @@ class WorkoutPlansProvider with ChangeNotifier { /// Fetch and set weight units for workout (kg, lb, plate, etc.) Future fetchAndSetRepetitionUnits() async { - final response = - await baseProvider.fetchPaginated(baseProvider.makeUrl(_repetitionUnitUrlPath)); + final response = await baseProvider + .fetchPaginated(baseProvider.makeUrl(_repetitionUnitUrlPath)); for (final unit in response) { _repetitionUnit.add(RepetitionUnit.fromJson(unit)); } @@ -322,7 +333,8 @@ class WorkoutPlansProvider with ChangeNotifier { /// Fetch and set weight units for workout (kg, lb, plate, etc.) Future fetchAndSetWeightUnits() async { - final response = await baseProvider.fetchPaginated(baseProvider.makeUrl(_weightUnitUrlPath)); + final response = await baseProvider + .fetchPaginated(baseProvider.makeUrl(_weightUnitUrlPath)); for (final unit in response) { _weightUnits.add(WeightUnit.fromJson(unit)); } @@ -354,7 +366,9 @@ class WorkoutPlansProvider with ChangeNotifier { // Save the result to the cache final exerciseData = { 'date': DateTime.now().toIso8601String(), - 'expiresIn': DateTime.now().add(const Duration(days: DAYS_TO_CACHE)).toIso8601String(), + 'expiresIn': DateTime.now() + .add(const Duration(days: DAYS_TO_CACHE)) + .toIso8601String(), 'repetitionUnits': _repetitionUnit.map((e) => e.toJson()).toList(), 'weightUnit': _weightUnits.map((e) => e.toJson()).toList(), }; @@ -525,7 +539,8 @@ class WorkoutPlansProvider with ChangeNotifier { log.id = newLog.id; log.weightUnit = _weightUnits.firstWhere((e) => e.id == log.weightUnitId); - log.repetitionUnit = _repetitionUnit.firstWhere((e) => e.id == log.weightUnitId); + log.repetitionUnit = + _repetitionUnit.firstWhere((e) => e.id == log.weightUnitId); log.exerciseBase = await _exercises.fetchAndSetExercise(log.exerciseBaseId); final plan = findById(log.workoutPlan); diff --git a/lib/screens/add_exercise_screen.dart b/lib/screens/add_exercise_screen.dart index 36695bb68..628baff19 100644 --- a/lib/screens/add_exercise_screen.dart +++ b/lib/screens/add_exercise_screen.dart @@ -25,7 +25,9 @@ class AddExerciseScreen extends StatelessWidget { Widget build(BuildContext context) { final profile = context.read().profile; - return profile!.isTrustworthy ? const AddExerciseStepper() : const EmailNotVerified(); + return profile!.isTrustworthy + ? const AddExerciseStepper() + : const EmailNotVerified(); } } @@ -70,22 +72,29 @@ class _AddExerciseStepperState extends State { setState(() { _isLoading = true; }); - final addExerciseProvider = context.read(); - final exerciseProvider = context.read(); + final addExerciseProvider = + context.read(); + final exerciseProvider = + context.read(); final baseId = await addExerciseProvider.addExercise(); - final base = await exerciseProvider.fetchAndSetExercise(baseId); - final name = base - .getExercise( - Localizations.localeOf(context).languageCode, - ) - .name; + final base = + await exerciseProvider.fetchAndSetExercise(baseId); + final name = context.mounted + ? base + .getExercise( + Localizations.localeOf(context).languageCode, + ) + .name + : null; setState(() { _isLoading = false; }); - if (!context.mounted) return; + if (!context.mounted) { + return; + } return showDialog( context: context, builder: (BuildContext context) { @@ -96,7 +105,7 @@ class _AddExerciseStepperState extends State { ), actions: [ TextButton( - child: Text(name), + child: Text(name ?? 'undefined'), onPressed: () { Navigator.of(context).pop(); Navigator.pushReplacementNamed( diff --git a/lib/screens/auth_screen.dart b/lib/screens/auth_screen.dart index aa61caba2..eca5ffcf6 100644 --- a/lib/screens/auth_screen.dart +++ b/lib/screens/auth_screen.dart @@ -197,7 +197,9 @@ class _AuthCardState extends State { // Check if update is required else continue normally if (res.containsKey('action')) { - if (res['action'] == LoginActions.update && mounted) { + if (res['action'] == LoginActions.update && + mounted && + context.mounted) { Navigator.of(context).push( MaterialPageRoute(builder: (context) => const UpdateAppScreen()), ); @@ -209,14 +211,14 @@ class _AuthCardState extends State { _isLoading = false; }); } on WgerHttpException catch (error) { - if (mounted) { + if (mounted && context.mounted) { showHttpExceptionErrorDialog(error, context); } setState(() { _isLoading = false; }); } catch (error) { - if (mounted) { + if (mounted && context.mounted) { showErrorDialog(error, context); } setState(() { @@ -317,7 +319,9 @@ class _AuthCardState extends State { labelText: AppLocalizations.of(context).password, prefixIcon: const Icon(Icons.password), suffixIcon: IconButton( - icon: Icon(isObscure ? Icons.visibility_off : Icons.visibility), + icon: Icon(isObscure + ? Icons.visibility_off + : Icons.visibility), onPressed: () { isObscure = !isObscure; updateState(() {}); @@ -344,10 +348,13 @@ class _AuthCardState extends State { return TextFormField( key: const Key('inputPassword2'), decoration: InputDecoration( - labelText: AppLocalizations.of(context).confirmPassword, + labelText: + AppLocalizations.of(context).confirmPassword, prefixIcon: const Icon(Icons.password), suffixIcon: IconButton( - icon: Icon(confirmIsObscure ? Icons.visibility_off : Icons.visibility), + icon: Icon(confirmIsObscure + ? Icons.visibility_off + : Icons.visibility), onPressed: () { confirmIsObscure = !confirmIsObscure; updateState(() {}); @@ -360,7 +367,8 @@ class _AuthCardState extends State { validator: _authMode == AuthMode.Signup ? (value) { if (value != _passwordController.text) { - return AppLocalizations.of(context).passwordsDontMatch; + return AppLocalizations.of(context) + .passwordsDontMatch; } return null; } @@ -378,8 +386,10 @@ class _AuthCardState extends State { child: TextFormField( key: const Key('inputServer'), decoration: InputDecoration( - labelText: AppLocalizations.of(context).customServerUrl, - helperText: AppLocalizations.of(context).customServerHint, + labelText: + AppLocalizations.of(context).customServerUrl, + helperText: + AppLocalizations.of(context).customServerHint, helperMaxLines: 4, ), controller: _serverUrlController, @@ -395,8 +405,10 @@ class _AuthCardState extends State { }, onSaved: (value) { // Remove any trailing slash - if (value!.lastIndexOf('/') == (value.length - 1)) { - value = value.substring(0, value.lastIndexOf('/')); + if (value!.lastIndexOf('/') == + (value.length - 1)) { + value = + value.substring(0, value.lastIndexOf('/')); } _authData['serverUrl'] = value; }, @@ -409,8 +421,9 @@ class _AuthCardState extends State { IconButton( icon: const Icon(Icons.undo), onPressed: () { - _serverUrlController.text = - kDebugMode ? DEFAULT_SERVER_TEST : DEFAULT_SERVER_PROD; + _serverUrlController.text = kDebugMode + ? DEFAULT_SERVER_TEST + : DEFAULT_SERVER_PROD; }, ), Text(AppLocalizations.of(context).reset), @@ -437,7 +450,8 @@ class _AuthCardState extends State { child: Center( child: _isLoading ? const CircularProgressIndicator( - valueColor: AlwaysStoppedAnimation(Colors.white), + valueColor: + AlwaysStoppedAnimation(Colors.white), ) : Text( _authMode == AuthMode.Login diff --git a/lib/screens/exercise_screen.dart b/lib/screens/exercise_screen.dart index d517f7995..f6100a372 100644 --- a/lib/screens/exercise_screen.dart +++ b/lib/screens/exercise_screen.dart @@ -31,7 +31,9 @@ class ExerciseDetailScreen extends StatelessWidget { return Scaffold( appBar: AppBar( - title: Text(exerciseBase.getExercise(Localizations.localeOf(context).languageCode).name), + title: Text(exerciseBase + .getExercise(Localizations.localeOf(context).languageCode) + .name), ), body: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), diff --git a/lib/screens/exercises_screen.dart b/lib/screens/exercises_screen.dart index ca6e33866..8ddc86de6 100644 --- a/lib/screens/exercises_screen.dart +++ b/lib/screens/exercises_screen.dart @@ -33,7 +33,8 @@ class _ExercisesScreenState extends State { @override Widget build(BuildContext context) { //final size = MediaQuery.of(context).size; - final exercisesList = Provider.of(context).filteredExercises; + final exercisesList = + Provider.of(context).filteredExercises; return Scaffold( appBar: EmptyAppBar(AppLocalizations.of(context).exercises), diff --git a/lib/screens/form_screen.dart b/lib/screens/form_screen.dart index 1ff100b2d..36654e981 100644 --- a/lib/screens/form_screen.dart +++ b/lib/screens/form_screen.dart @@ -56,7 +56,8 @@ class FormScreen extends StatelessWidget { appBar: AppBar(title: Text(args.title)), body: args.hasListView ? Scrollable( - viewportBuilder: (BuildContext context, ViewportOffset position) => Padding( + viewportBuilder: + (BuildContext context, ViewportOffset position) => Padding( padding: args.padding, child: args.widget, ), diff --git a/lib/screens/home_tabs_screen.dart b/lib/screens/home_tabs_screen.dart index 765703be5..a21c4fda5 100644 --- a/lib/screens/home_tabs_screen.dart +++ b/lib/screens/home_tabs_screen.dart @@ -45,7 +45,8 @@ class HomeTabsScreen extends StatefulWidget { _HomeTabsScreenState createState() => _HomeTabsScreenState(); } -class _HomeTabsScreenState extends State with SingleTickerProviderStateMixin { +class _HomeTabsScreenState extends State + with SingleTickerProviderStateMixin { late Future _initialData; int _selectedIndex = 0; diff --git a/lib/screens/log_meal_screen.dart b/lib/screens/log_meal_screen.dart index d93fbe131..04f319f3b 100644 --- a/lib/screens/log_meal_screen.dart +++ b/lib/screens/log_meal_screen.dart @@ -47,7 +47,8 @@ class _LogMealScreenState extends State { final args = ModalRoute.of(context)!.settings.arguments as LogMealArguments; final meal = args.meal.copyWith( mealItems: args.meal.mealItems - .map((mealItem) => mealItem.copyWith(amount: mealItem.amount * portionPct / 100)) + .map((mealItem) => + mealItem.copyWith(amount: mealItem.amount * portionPct / 100)) .toList(), ); @@ -64,13 +65,16 @@ class _LogMealScreenState extends State { style: Theme.of(context).textTheme.headlineSmall, ), if (meal.mealItems.isEmpty) - ListTile(title: Text(AppLocalizations.of(context).noIngredientsDefined)) + ListTile( + title: Text( + AppLocalizations.of(context).noIngredientsDefined)) else Column( children: [ const DiaryheaderTile(), ...meal.mealItems.map( - (item) => MealItemEditableFullTile(item, viewMode.withAllDetails, false), + (item) => MealItemEditableFullTile( + item, viewMode.withAllDetails, false), ), const SizedBox(height: 32), Text( @@ -81,7 +85,8 @@ class _LogMealScreenState extends State { min: 0, max: 150, divisions: 30, - onChanged: (value) => setState(() => portionPct = value), + onChanged: (value) => + setState(() => portionPct = value), value: portionPct, ), ], @@ -93,23 +98,25 @@ class _LogMealScreenState extends State { TextButton( child: const Text('Log'), onPressed: () async { - await Provider.of( - context, - listen: false, - ).logMealToDiary(meal); - // ignore: use_build_context_synchronously - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - // ignore: use_build_context_synchronously - AppLocalizations.of(context).mealLogged, - textAlign: TextAlign.center, - ), - ), - ); - Navigator.of(context).pop(); - if (args.popTwice) { - Navigator.of(context).pop(); + if (context.mounted) { + await Provider.of( + context, + listen: false, + ).logMealToDiary(meal); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + AppLocalizations.of(context).mealLogged, + textAlign: TextAlign.center, + ), + ), + ); + Navigator.of(context).pop(); + if (args.popTwice) { + Navigator.of(context).pop(); + } + } } }, ), diff --git a/lib/screens/log_meals_screen.dart b/lib/screens/log_meals_screen.dart index 74aea3897..72387a293 100644 --- a/lib/screens/log_meals_screen.dart +++ b/lib/screens/log_meals_screen.dart @@ -34,7 +34,8 @@ class _LogMealsScreenState extends State { @override Widget build(BuildContext context) { - final nutritionalPlan = ModalRoute.of(context)!.settings.arguments as NutritionalPlan; + final nutritionalPlan = + ModalRoute.of(context)!.settings.arguments as NutritionalPlan; return Scaffold( appBar: AppBar( diff --git a/lib/screens/measurement_entries_screen.dart b/lib/screens/measurement_entries_screen.dart index 3c8e41889..312601981 100644 --- a/lib/screens/measurement_entries_screen.dart +++ b/lib/screens/measurement_entries_screen.dart @@ -36,7 +36,8 @@ class MeasurementEntriesScreen extends StatelessWidget { @override Widget build(BuildContext context) { final categoryId = ModalRoute.of(context)!.settings.arguments as int; - final category = Provider.of(context).findCategoryById(categoryId); + final category = + Provider.of(context).findCategoryById(categoryId); return Scaffold( appBar: AppBar( @@ -63,11 +64,13 @@ class MeasurementEntriesScreen extends StatelessWidget { builder: (BuildContext contextDialog) { return AlertDialog( content: Text( - AppLocalizations.of(context).confirmDelete(category.name), + AppLocalizations.of(context) + .confirmDelete(category.name), ), actions: [ TextButton( - child: Text(MaterialLocalizations.of(context).cancelButtonLabel), + child: Text(MaterialLocalizations.of(context) + .cancelButtonLabel), onPressed: () => Navigator.of(contextDialog).pop(), ), TextButton( @@ -91,7 +94,8 @@ class MeasurementEntriesScreen extends StatelessWidget { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( - AppLocalizations.of(context).successfullyDeleted, + AppLocalizations.of(context) + .successfullyDeleted, textAlign: TextAlign.center, ), ), diff --git a/lib/screens/nutritional_diary_screen.dart b/lib/screens/nutritional_diary_screen.dart index 4e60f44f0..a0c35350e 100644 --- a/lib/screens/nutritional_diary_screen.dart +++ b/lib/screens/nutritional_diary_screen.dart @@ -40,11 +40,13 @@ class NutritionalDiaryScreen extends StatelessWidget { @override Widget build(BuildContext context) { - final args = ModalRoute.of(context)!.settings.arguments as NutritionalDiaryArguments; + final args = + ModalRoute.of(context)!.settings.arguments as NutritionalDiaryArguments; return Scaffold( appBar: AppBar( - title: Text(DateFormat.yMd(Localizations.localeOf(context).languageCode).format(args.date)), + title: Text(DateFormat.yMd(Localizations.localeOf(context).languageCode) + .format(args.date)), ), body: Consumer( builder: (context, nutritionProvider, child) => SingleChildScrollView( diff --git a/lib/screens/nutritional_plan_screen.dart b/lib/screens/nutritional_plan_screen.dart index 6d695a299..69fa2fc4d 100644 --- a/lib/screens/nutritional_plan_screen.dart +++ b/lib/screens/nutritional_plan_screen.dart @@ -37,13 +37,15 @@ class NutritionalPlanScreen extends StatelessWidget { static const routeName = '/nutritional-plan-detail'; Future _loadFullPlan(BuildContext context, int planId) { - return Provider.of(context, listen: false).fetchAndSetPlanFull(planId); + return Provider.of(context, listen: false) + .fetchAndSetPlanFull(planId); } @override Widget build(BuildContext context) { const appBarForeground = Colors.white; - final nutritionalPlan = ModalRoute.of(context)!.settings.arguments as NutritionalPlan; + final nutritionalPlan = + ModalRoute.of(context)!.settings.arguments as NutritionalPlan; return Scaffold( //appBar: getAppBar(nutritionalPlan), @@ -119,13 +121,14 @@ class NutritionalPlanScreen extends StatelessWidget { FormScreen.routeName, arguments: FormScreenArguments( AppLocalizations.of(context).edit, - PlanForm(nutritionalPlan), + PlanForm(plan: nutritionalPlan), hasListView: true, ), ); break; case NutritionalPlanOptions.delete: - Provider.of(context, listen: false) + Provider.of(context, + listen: false) .deletePlan(nutritionalPlan.id!); Navigator.of(context).pop(); break; @@ -156,7 +159,10 @@ class NutritionalPlanScreen extends StatelessWidget { titlePadding: const EdgeInsets.fromLTRB(56, 0, 56, 16), title: Text( nutritionalPlan.getLabel(context), - style: Theme.of(context).textTheme.titleLarge?.copyWith(color: appBarForeground), + style: Theme.of(context) + .textTheme + .titleLarge + ?.copyWith(color: appBarForeground), ), ), ), diff --git a/lib/screens/nutritional_plans_screen.dart b/lib/screens/nutritional_plans_screen.dart index 43ce024c4..531b83d71 100644 --- a/lib/screens/nutritional_plans_screen.dart +++ b/lib/screens/nutritional_plans_screen.dart @@ -42,13 +42,16 @@ class NutritionalPlansScreen extends StatelessWidget { arguments: FormScreenArguments( AppLocalizations.of(context).newNutritionalPlan, hasListView: true, - PlanForm(), + PlanForm( + plan: null, + ), ), ); }, ), body: Consumer( - builder: (context, nutritionProvider, child) => NutritionalPlansList(nutritionProvider), + builder: (context, nutritionProvider, child) => + NutritionalPlansList(nutritionProvider), ), ); } diff --git a/lib/screens/weight_screen.dart b/lib/screens/weight_screen.dart index ff87fc6d1..3392f1eee 100644 --- a/lib/screens/weight_screen.dart +++ b/lib/screens/weight_screen.dart @@ -44,7 +44,8 @@ class WeightScreen extends StatelessWidget { FormScreen.routeName, arguments: FormScreenArguments( AppLocalizations.of(context).newEntry, - WeightForm(lastWeightEntry?.copyWith(id: null, date: DateTime.now())), + WeightForm( + lastWeightEntry?.copyWith(id: null, date: DateTime.now())), ), ); }, diff --git a/lib/screens/workout_plan_screen.dart b/lib/screens/workout_plan_screen.dart index 61f898b7f..ba45cdc5e 100644 --- a/lib/screens/workout_plan_screen.dart +++ b/lib/screens/workout_plan_screen.dart @@ -72,7 +72,8 @@ class _WorkoutPlanScreenState extends State { @override Widget build(BuildContext context) { const appBarForeground = Colors.white; - final workoutPlan = ModalRoute.of(context)!.settings.arguments as WorkoutPlan; + final workoutPlan = + ModalRoute.of(context)!.settings.arguments as WorkoutPlan; return Scaffold( body: CustomScrollView( @@ -85,7 +86,10 @@ class _WorkoutPlanScreenState extends State { titlePadding: const EdgeInsets.fromLTRB(56, 0, 56, 16), title: Text( workoutPlan.name, - style: Theme.of(context).textTheme.titleLarge?.copyWith(color: appBarForeground), + style: Theme.of(context) + .textTheme + .titleLarge + ?.copyWith(color: appBarForeground), ), ), actions: [ @@ -130,7 +134,8 @@ class _WorkoutPlanScreenState extends State { ), FutureBuilder( future: _loadFullWorkout(context, workoutPlan.id!), - builder: (context, AsyncSnapshot snapshot) => SliverList( + builder: (context, AsyncSnapshot snapshot) => + SliverList( delegate: SliverChildListDelegate( [ if (snapshot.connectionState == ConnectionState.waiting) diff --git a/lib/screens/workout_plans_screen.dart b/lib/screens/workout_plans_screen.dart index 7f2490e9f..ab0fb264d 100644 --- a/lib/screens/workout_plans_screen.dart +++ b/lib/screens/workout_plans_screen.dart @@ -48,7 +48,8 @@ class WorkoutPlansScreen extends StatelessWidget { child: const Icon(Icons.add, color: Colors.white), ), body: Consumer( - builder: (context, workoutProvider, child) => WorkoutPlansList(workoutProvider), + builder: (context, workoutProvider, child) => + WorkoutPlansList(workoutProvider), ), ); } diff --git a/lib/theme/theme.dart b/lib/theme/theme.dart index ba0706e70..9abecfafc 100644 --- a/lib/theme/theme.dart +++ b/lib/theme/theme.dart @@ -35,7 +35,6 @@ const FlexSubThemesData wgerSubThemeData = FlexSubThemesData( fabSchemeColor: SchemeColor.secondary, inputDecoratorBorderType: FlexInputBorderType.underline, inputDecoratorIsFilled: false, - useTextTheme: true, appBarScrolledUnderElevation: 4, navigationBarIndicatorOpacity: 0.24, navigationBarHeight: 56, diff --git a/lib/widgets/add_exercise/add_exercise_dropdown_button.dart b/lib/widgets/add_exercise/add_exercise_dropdown_button.dart index 7b8d71dd7..0ace57444 100644 --- a/lib/widgets/add_exercise/add_exercise_dropdown_button.dart +++ b/lib/widgets/add_exercise/add_exercise_dropdown_button.dart @@ -17,7 +17,8 @@ class AddExerciseDropdownButton extends StatefulWidget { final FormFieldSetter? onSaved; @override - _AddExerciseDropdownButtonState createState() => _AddExerciseDropdownButtonState(); + _AddExerciseDropdownButtonState createState() => + _AddExerciseDropdownButtonState(); } class _AddExerciseDropdownButtonState extends State { @@ -39,7 +40,8 @@ class _AddExerciseDropdownButtonState extends State { }, value: _selectedItem, decoration: InputDecoration( - contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + contentPadding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 10), border: const OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10)), ), diff --git a/lib/widgets/add_exercise/add_exercise_multiselect_button.dart b/lib/widgets/add_exercise/add_exercise_multiselect_button.dart index 6af8a6844..18a16f323 100644 --- a/lib/widgets/add_exercise/add_exercise_multiselect_button.dart +++ b/lib/widgets/add_exercise/add_exercise_multiselect_button.dart @@ -20,10 +20,12 @@ class AddExerciseMultiselectButton extends StatefulWidget { }); @override - _AddExerciseMultiselectButtonState createState() => _AddExerciseMultiselectButtonState(); + _AddExerciseMultiselectButtonState createState() => + _AddExerciseMultiselectButtonState(); } -class _AddExerciseMultiselectButtonState extends State { +class _AddExerciseMultiselectButtonState + extends State { List _selectedItems = []; @override @@ -33,8 +35,9 @@ class _AddExerciseMultiselectButtonState extends State MultiSelectItem(item, widget.displayName(item))).toList(), + items: widget.items + .map((item) => MultiSelectItem(item, widget.displayName(item))) + .toList(), onConfirm: (value) { setState(() { _selectedItems = value.cast(); diff --git a/lib/widgets/add_exercise/add_exercise_text_area.dart b/lib/widgets/add_exercise/add_exercise_text_area.dart index 7bad7be62..675ac1b78 100644 --- a/lib/widgets/add_exercise/add_exercise_text_area.dart +++ b/lib/widgets/add_exercise/add_exercise_text_area.dart @@ -28,13 +28,15 @@ class AddExerciseTextArea extends StatelessWidget { return Padding( padding: const EdgeInsets.all(8.0), child: TextFormField( - keyboardType: isMultiline ? TextInputType.multiline : TextInputType.text, + keyboardType: + isMultiline ? TextInputType.multiline : TextInputType.text, maxLines: isMultiline ? null : DEFAULT_LINES, minLines: isMultiline ? MULTILINE_MIN_LINES : DEFAULT_LINES, validator: validator, onSaved: onSaved, decoration: InputDecoration( - contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + contentPadding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 10), border: const OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10)), ), diff --git a/lib/widgets/add_exercise/mixins/image_picker_mixin.dart b/lib/widgets/add_exercise/mixins/image_picker_mixin.dart index d98a235ee..f0781c841 100644 --- a/lib/widgets/add_exercise/mixins/image_picker_mixin.dart +++ b/lib/widgets/add_exercise/mixins/image_picker_mixin.dart @@ -17,7 +17,8 @@ mixin ExerciseImagePickerMixin { bool _validateFileType(File file) { final extension = file.path.split('.').last; - return validFileExtensions.any((element) => extension == element.toLowerCase()); + return validFileExtensions + .any((element) => extension == element.toLowerCase()); } void pickImages(BuildContext context, {bool pickFromCamera = false}) async { @@ -25,7 +26,8 @@ mixin ExerciseImagePickerMixin { List? images; if (pickFromCamera) { - final pictureTaken = await imagePicker.pickImage(source: ImageSource.camera); + final pictureTaken = + await imagePicker.pickImage(source: ImageSource.camera); images = pictureTaken == null ? null : [pictureTaken]; } else { images = await imagePicker.pickMultiImage(); @@ -50,12 +52,15 @@ mixin ExerciseImagePickerMixin { if (!isFileValid) { if (context.mounted) { - showDialog(context: context, builder: (context) => Text(errorMessage)); + showDialog( + context: context, builder: (context) => Text(errorMessage)); } return; } } - context.read().addExerciseImages(selectedImages); + if (context.mounted) { + context.read().addExerciseImages(selectedImages); + } } } } diff --git a/lib/widgets/add_exercise/preview_images.dart b/lib/widgets/add_exercise/preview_images.dart index 32cd2d236..6ab89c5aa 100644 --- a/lib/widgets/add_exercise/preview_images.dart +++ b/lib/widgets/add_exercise/preview_images.dart @@ -6,7 +6,8 @@ import 'package:wger/providers/add_exercise.dart'; import 'mixins/image_picker_mixin.dart'; -class PreviewExerciseImages extends StatelessWidget with ExerciseImagePickerMixin { +class PreviewExerciseImages extends StatelessWidget + with ExerciseImagePickerMixin { const PreviewExerciseImages({super.key, required this.selectedImages}); final List selectedImages; @@ -31,12 +32,14 @@ class PreviewExerciseImages extends StatelessWidget with ExerciseImagePickerMixi child: Container( decoration: BoxDecoration( color: Colors.grey.withValues(alpha: 0.5), - borderRadius: const BorderRadius.all(Radius.circular(20)), + borderRadius: + const BorderRadius.all(Radius.circular(20)), ), child: IconButton( iconSize: 20, - onPressed: () => - context.read().removeExercise(file.path), + onPressed: () => context + .read() + .removeExercise(file.path), color: Colors.white, icon: const Icon(Icons.delete), ), diff --git a/lib/widgets/add_exercise/steps/step1basics.dart b/lib/widgets/add_exercise/steps/step1basics.dart index 0d875947f..399e08eda 100644 --- a/lib/widgets/add_exercise/steps/step1basics.dart +++ b/lib/widgets/add_exercise/steps/step1basics.dart @@ -35,15 +35,16 @@ class Step1Basics extends StatelessWidget { helperText: AppLocalizations.of(context).baseNameEnglish, isRequired: true, validator: (name) => validateName(name, context), - onSaved: (String? name) => addExerciseProvider.exerciseNameEn = name!, + onSaved: (String? name) => + addExerciseProvider.exerciseNameEn = name!, ), AddExerciseTextArea( onChange: (value) => {}, title: AppLocalizations.of(context).alternativeNames, isMultiline: true, helperText: AppLocalizations.of(context).oneNamePerLine, - onSaved: (String? alternateName) => - addExerciseProvider.alternateNamesEn = alternateName!.split('\n'), + onSaved: (String? alternateName) => addExerciseProvider + .alternateNamesEn = alternateName!.split('\n'), ), ExerciseCategoryInputWidget( key: const Key('category-dropdown'), @@ -57,7 +58,8 @@ class Step1Basics extends StatelessWidget { return AppLocalizations.of(context).selectEntry; } }, - displayName: (ExerciseCategory c) => getTranslation(c.name, context), + displayName: (ExerciseCategory c) => + getTranslation(c.name, context), ), AddExerciseMultiselectButton( key: const Key('equipment-multiselect'), @@ -84,7 +86,10 @@ class Step1Basics extends StatelessWidget { addExerciseProvider.primaryMuscles = muscles.cast(); }, displayName: (Muscle e) => - e.name + (e.nameEn.isNotEmpty ? '\n(${getTranslation(e.nameEn, context)})' : ''), + e.name + + (e.nameEn.isNotEmpty + ? '\n(${getTranslation(e.nameEn, context)})' + : ''), ), AddExerciseMultiselectButton( key: const Key('secondary-muscles-multiselect'), @@ -98,7 +103,10 @@ class Step1Basics extends StatelessWidget { addExerciseProvider.secondaryMuscles = muscles.cast(); }, displayName: (Muscle e) => - e.name + (e.nameEn.isNotEmpty ? '\n(${getTranslation(e.nameEn, context)})' : ''), + e.name + + (e.nameEn.isNotEmpty + ? '\n(${getTranslation(e.nameEn, context)})' + : ''), ), Consumer( builder: (context, value, child) => MuscleRowWidget( diff --git a/lib/widgets/add_exercise/steps/step2variations.dart b/lib/widgets/add_exercise/steps/step2variations.dart index fb2fb5b7e..84b9b4eb0 100644 --- a/lib/widgets/add_exercise/steps/step2variations.dart +++ b/lib/widgets/add_exercise/steps/step2variations.dart @@ -37,11 +37,13 @@ class Step2Variations extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, //mainAxisSize: MainAxisSize.max, children: [ - ...exerciseProvider.exerciseBasesByVariation[key]!.map( + ...exerciseProvider.exerciseBasesByVariation[key]! + .map( (base) => Text( base .getExercise( - Localizations.localeOf(context).languageCode, + Localizations.localeOf(context) + .languageCode, ) .name, overflow: TextOverflow.ellipsis, @@ -61,7 +63,9 @@ class Step2Variations extends StatelessWidget { ), ), // Exercise bases without variations - ...exerciseProvider.exercises.where((b) => b.variationId == null).map( + ...exerciseProvider.exercises + .where((b) => b.variationId == null) + .map( (base) => Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -73,7 +77,8 @@ class Step2Variations extends StatelessWidget { Text( base .getExercise( - Localizations.localeOf(context).languageCode, + Localizations.localeOf(context) + .languageCode, ) .name, overflow: TextOverflow.ellipsis, @@ -84,8 +89,10 @@ class Step2Variations extends StatelessWidget { ), Consumer( builder: (ctx, provider, __) => Switch( - value: provider.newVariationForExercise == base.id, - onChanged: (state) => provider.newVariationForExercise = base.id, + value: + provider.newVariationForExercise == base.id, + onChanged: (state) => + provider.newVariationForExercise = base.id, ), ), ], diff --git a/lib/widgets/add_exercise/steps/step3description.dart b/lib/widgets/add_exercise/steps/step3description.dart index fad46ba86..c0632cfea 100644 --- a/lib/widgets/add_exercise/steps/step3description.dart +++ b/lib/widgets/add_exercise/steps/step3description.dart @@ -23,7 +23,8 @@ class Step3Description extends StatelessWidget { isRequired: true, isMultiline: true, validator: (name) => validateDescription(name, context), - onSaved: (String? description) => addExerciseProvider.descriptionEn = description!, + onSaved: (String? description) => + addExerciseProvider.descriptionEn = description!, ), ], ), diff --git a/lib/widgets/add_exercise/steps/step4translations.dart b/lib/widgets/add_exercise/steps/step4translations.dart index 284ed62dd..9763e22a8 100644 --- a/lib/widgets/add_exercise/steps/step4translations.dart +++ b/lib/widgets/add_exercise/steps/step4translations.dart @@ -61,7 +61,8 @@ class _Step4TranslationState extends State { title: '${AppLocalizations.of(context).name}*', isRequired: true, validator: (name) => validateName(name, context), - onSaved: (String? name) => addExerciseProvider.exerciseNameTrans = name!, + onSaved: (String? name) => + addExerciseProvider.exerciseNameTrans = name!, ), AddExerciseTextArea( onChange: (value) => {}, @@ -73,7 +74,8 @@ class _Step4TranslationState extends State { if (alternateNames?.isNotEmpty == true) { final names = alternateNames!.split('\n'); for (final name in names) { - if (name.length < MIN_CHARS_NAME || name.length > MAX_CHARS_NAME) { + if (name.length < MIN_CHARS_NAME || + name.length > MAX_CHARS_NAME) { return AppLocalizations.of(context).enterCharacters( MIN_CHARS_NAME, MAX_CHARS_NAME, @@ -83,8 +85,8 @@ class _Step4TranslationState extends State { } return null; }, - onSaved: (String? alternateName) => - addExerciseProvider.alternateNamesTrans = alternateName!.split('\n'), + onSaved: (String? alternateName) => addExerciseProvider + .alternateNamesTrans = alternateName!.split('\n'), ), AddExerciseTextArea( onChange: (value) => {}, diff --git a/lib/widgets/add_exercise/steps/step5images.dart b/lib/widgets/add_exercise/steps/step5images.dart index eb3b3bdd2..880d56518 100644 --- a/lib/widgets/add_exercise/steps/step5images.dart +++ b/lib/widgets/add_exercise/steps/step5images.dart @@ -13,7 +13,8 @@ class Step5Images extends StatefulWidget { State createState() => _Step5ImagesState(); } -class _Step5ImagesState extends State with ExerciseImagePickerMixin { +class _Step5ImagesState extends State + with ExerciseImagePickerMixin { @override Widget build(BuildContext context) { return Form( @@ -33,7 +34,8 @@ class _Step5ImagesState extends State with ExerciseImagePickerMixin mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( - onPressed: () => pickImages(context, pickFromCamera: true), + onPressed: () => + pickImages(context, pickFromCamera: true), icon: const Icon(Icons.camera_alt), ), IconButton( diff --git a/lib/widgets/core/about.dart b/lib/widgets/core/about.dart index 385690cb6..29a4511c4 100644 --- a/lib/widgets/core/about.dart +++ b/lib/widgets/core/about.dart @@ -111,7 +111,10 @@ class AboutPage extends StatelessWidget { SizedBox(height: 0.025 * deviceSize.height), Text( AppLocalizations.of(context).aboutDescription, - style: Theme.of(context).textTheme.bodyMedium!.copyWith(fontSize: 16), + style: Theme.of(context) + .textTheme + .bodyMedium! + .copyWith(fontSize: 16), ), const SizedBox(height: 10), AboutEntry( @@ -163,7 +166,8 @@ class AboutPage extends StatelessWidget { showLicensePage( context: context, applicationName: 'wger', - applicationVersion: 'App: ${authProvider.applicationVersion!.version}\n' + applicationVersion: + 'App: ${authProvider.applicationVersion!.version}\n' 'Server: ${authProvider.serverVersion}', applicationLegalese: '\u{a9} 2020 - 2021 contributors', applicationIcon: Padding( diff --git a/lib/widgets/core/app_bar.dart b/lib/widgets/core/app_bar.dart index e82f242f7..7ce964c18 100644 --- a/lib/widgets/core/app_bar.dart +++ b/lib/widgets/core/app_bar.dart @@ -77,13 +77,16 @@ class MainAppBar extends StatelessWidget implements PreferredSizeWidget { ), ListTile( leading: const Icon(Icons.settings), - onTap: () => Navigator.of(context).pushNamed(SettingsPage.routeName), + onTap: () => Navigator.of(context) + .pushNamed(SettingsPage.routeName), title: Text(AppLocalizations.of(context).settingsTitle), ), ListTile( leading: const Icon(Icons.info), - onTap: () => Navigator.of(context).pushNamed(AboutPage.routeName), - title: Text(AppLocalizations.of(context).aboutPageTitle), + onTap: () => Navigator.of(context) + .pushNamed(AboutPage.routeName), + title: + Text(AppLocalizations.of(context).aboutPageTitle), ), const Divider(), ListTile( diff --git a/lib/widgets/core/core.dart b/lib/widgets/core/core.dart index 4f3ff958d..d61aa67f6 100644 --- a/lib/widgets/core/core.dart +++ b/lib/widgets/core/core.dart @@ -50,7 +50,7 @@ class Pill extends StatelessWidget { return Container( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 7), decoration: BoxDecoration( - color: Theme.of(context).primaryColorLight.withOpacity(0.15), + color: Theme.of(context).primaryColorLight.withValues(alpha: .15), border: Border.all(color: Colors.grey[300]!), borderRadius: BorderRadius.circular(5), ), @@ -65,7 +65,8 @@ class CircleIconAvatar extends StatelessWidget { final Color color; - const CircleIconAvatar(this._icon, {this.radius = 20, this.color = Colors.black12}); + const CircleIconAvatar(this._icon, + {this.radius = 20, this.color = Colors.black12}); @override Widget build(BuildContext context) { diff --git a/lib/widgets/core/settings.dart b/lib/widgets/core/settings.dart index 78c8dfa9e..d1adba279 100644 --- a/lib/widgets/core/settings.dart +++ b/lib/widgets/core/settings.dart @@ -30,8 +30,10 @@ class SettingsPage extends StatelessWidget { @override Widget build(BuildContext context) { - final exerciseProvider = Provider.of(context, listen: false); - final nutritionProvider = Provider.of(context, listen: false); + final exerciseProvider = + Provider.of(context, listen: false); + final nutritionProvider = + Provider.of(context, listen: false); return Scaffold( appBar: AppBar( @@ -40,7 +42,8 @@ class SettingsPage extends StatelessWidget { body: ListView( children: [ ListTile( - title: Text(AppLocalizations.of(context).settingsExerciseCacheDescription), + title: Text( + AppLocalizations.of(context).settingsExerciseCacheDescription), trailing: IconButton( key: const ValueKey('cacheIconExercises'), icon: const Icon(Icons.delete), @@ -49,7 +52,8 @@ class SettingsPage extends StatelessWidget { if (context.mounted) { final snackBar = SnackBar( - content: Text(AppLocalizations.of(context).settingsCacheDeletedSnackbar), + content: Text(AppLocalizations.of(context) + .settingsCacheDeletedSnackbar), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); @@ -58,7 +62,8 @@ class SettingsPage extends StatelessWidget { ), ), ListTile( - title: Text(AppLocalizations.of(context).settingsIngredientCacheDescription), + title: Text(AppLocalizations.of(context) + .settingsIngredientCacheDescription), trailing: IconButton( key: const ValueKey('cacheIconIngredients'), icon: const Icon(Icons.delete), @@ -67,7 +72,8 @@ class SettingsPage extends StatelessWidget { if (context.mounted) { final snackBar = SnackBar( - content: Text(AppLocalizations.of(context).settingsCacheDeletedSnackbar), + content: Text(AppLocalizations.of(context) + .settingsCacheDeletedSnackbar), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); diff --git a/lib/widgets/dashboard/calendar.dart b/lib/widgets/dashboard/calendar.dart index 9c1eb232e..0ae9af59f 100644 --- a/lib/widgets/dashboard/calendar.dart +++ b/lib/widgets/dashboard/calendar.dart @@ -1,3 +1,5 @@ +// ignore_for_file: use_build_context_synchronously + /* * This file is part of wger Workout Manager . * Copyright (C) 2020, 2021 wger Team @@ -58,15 +60,16 @@ class DashboardCalendarWidget extends StatefulWidget { const DashboardCalendarWidget(); @override - _DashboardCalendarWidgetState createState() => _DashboardCalendarWidgetState(); + _DashboardCalendarWidgetState createState() => + _DashboardCalendarWidgetState(); } class _DashboardCalendarWidgetState extends State with TickerProviderStateMixin { late Map> _events; late final ValueNotifier> _selectedEvents; - RangeSelectionMode _rangeSelectionMode = - RangeSelectionMode.toggledOff; // Can be toggled on/off by longpressing a date + RangeSelectionMode _rangeSelectionMode = RangeSelectionMode + .toggledOff; // Can be toggled on/off by longpressing a date DateTime _focusedDay = DateTime.now(); DateTime? _selectedDay; DateTime? _rangeStart; @@ -116,7 +119,8 @@ class _DashboardCalendarWidgetState extends State } // Process workout sessions - final WorkoutPlansProvider plans = Provider.of(context, listen: false); + final WorkoutPlansProvider plans = + Provider.of(context, listen: false); await plans.fetchSessionData().then((entries) { for (final entry in entries['results']) { final session = WorkoutSession.fromJson(entry); @@ -125,9 +129,11 @@ class _DashboardCalendarWidgetState extends State _events[date] = []; } var time = ''; - time = '(${timeToString(session.timeStart)} - ${timeToString(session.timeEnd)})'; + time = + '(${timeToString(session.timeStart)} - ${timeToString(session.timeEnd)})'; // Add events to lists + _events[date]!.add(Event( EventType.session, '${AppLocalizations.of(context).impression}: ${session.impressionAsString} $time', @@ -251,7 +257,8 @@ class _DashboardCalendarWidgetState extends State title: Text((() { switch (event.type) { case EventType.caloriesDiary: - return AppLocalizations.of(context).nutritionalDiary; + return AppLocalizations.of(context) + .nutritionalDiary; case EventType.session: return AppLocalizations.of(context).workoutSession; diff --git a/lib/widgets/dashboard/widgets.dart b/lib/widgets/dashboard/widgets.dart index 3d08390aa..f7eb4d4f6 100644 --- a/lib/widgets/dashboard/widgets.dart +++ b/lib/widgets/dashboard/widgets.dart @@ -52,7 +52,8 @@ class DashboardNutritionWidget extends StatefulWidget { const DashboardNutritionWidget(); @override - _DashboardNutritionWidgetState createState() => _DashboardNutritionWidgetState(); + _DashboardNutritionWidgetState createState() => + _DashboardNutritionWidgetState(); } class _DashboardNutritionWidgetState extends State { @@ -62,7 +63,8 @@ class _DashboardNutritionWidgetState extends State { @override void initState() { super.initState(); - _plan = Provider.of(context, listen: false).currentPlan; + _plan = + Provider.of(context, listen: false).currentPlan; _hasContent = _plan != null; } @@ -73,7 +75,9 @@ class _DashboardNutritionWidgetState extends State { children: [ ListTile( title: Text( - _hasContent ? _plan!.description : AppLocalizations.of(context).nutritionalPlan, + _hasContent + ? _plan!.description + : AppLocalizations.of(context).nutritionalPlan, style: Theme.of(context).textTheme.headlineSmall, ), subtitle: Text( @@ -91,7 +95,8 @@ class _DashboardNutritionWidgetState extends State { Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Container( - padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 15), + padding: + const EdgeInsets.symmetric(horizontal: 5, vertical: 15), child: FlNutritionalPlanGoalWidget(nutritionalPlan: _plan!), ), ) @@ -138,7 +143,8 @@ class _DashboardNutritionWidgetState extends State { ), tooltip: AppLocalizations.of(context).logMeal, onPressed: () { - Navigator.of(context).pushNamed(LogMealsScreen.routeName, arguments: _plan); + Navigator.of(context) + .pushNamed(LogMealsScreen.routeName, arguments: _plan); }, ), ], @@ -163,7 +169,9 @@ class _DashboardWeightWidgetState extends State { final weightProvider = context.read(); final (entriesAll, entries7dAvg) = sensibleRange( - weightProvider.items.map((e) => MeasurementChartEntry(e.weight, e.date)).toList(), + weightProvider.items + .map((e) => MeasurementChartEntry(e.weight, e.date)) + .toList(), ); return Consumer( @@ -208,7 +216,8 @@ class _DashboardWeightWidgetState extends State { AppLocalizations.of(context).goToDetailPage, ), onPressed: () { - Navigator.of(context).pushNamed(WeightScreen.routeName); + Navigator.of(context) + .pushNamed(WeightScreen.routeName); }, ), IconButton( @@ -221,7 +230,8 @@ class _DashboardWeightWidgetState extends State { AppLocalizations.of(context).newEntry, WeightForm(weightProvider .getNewestEntry() - ?.copyWith(id: null, date: DateTime.now())), + ?.copyWith( + id: null, date: DateTime.now())), ), ); }, @@ -249,10 +259,12 @@ class DashboardMeasurementWidget extends StatefulWidget { const DashboardMeasurementWidget(); @override - _DashboardMeasurementWidgetState createState() => _DashboardMeasurementWidgetState(); + _DashboardMeasurementWidgetState createState() => + _DashboardMeasurementWidgetState(); } -class _DashboardMeasurementWidgetState extends State { +class _DashboardMeasurementWidgetState + extends State { int _current = 0; final _controller = CarouselSliderController(); @@ -260,8 +272,9 @@ class _DashboardMeasurementWidgetState extends State Widget build(BuildContext context) { final provider = Provider.of(context, listen: false); - final items = - provider.categories.map((item) => CategoriesCard(item, elevation: 0)).toList(); + final items = provider.categories + .map((item) => CategoriesCard(item, elevation: 0)) + .toList(); if (items.isNotEmpty) { items.add( NothingFound( @@ -333,10 +346,14 @@ class _DashboardMeasurementWidgetState extends State ), decoration: BoxDecoration( shape: BoxShape.circle, - color: - Theme.of(context).textTheme.headlineSmall!.color!.withOpacity( + color: Theme.of(context) + .textTheme + .headlineSmall! + .color! + .withValues( + alpha: _current == entry.key ? 0.9 : 0.4, - ), + ), ), ), ); @@ -406,7 +423,8 @@ class _DashboardWorkoutWidgetState extends State { icon: const Icon(Icons.play_arrow), color: wgerPrimaryButtonColor, onPressed: () { - Navigator.of(context).pushNamed(GymModeScreen.routeName, arguments: day); + Navigator.of(context) + .pushNamed(GymModeScreen.routeName, arguments: day); }, ), ], @@ -427,7 +445,8 @@ class _DashboardWorkoutWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(s.exerciseObj - .getExercise(Localizations.localeOf(context).languageCode) + .getExercise(Localizations.localeOf(context) + .languageCode) .name), const SizedBox(width: 10), MutedText( @@ -457,7 +476,9 @@ class _DashboardWorkoutWidgetState extends State { children: [ ListTile( title: Text( - _hasContent ? _workoutPlan!.name : AppLocalizations.of(context).labelWorkoutPlan, + _hasContent + ? _workoutPlan!.name + : AppLocalizations.of(context).labelWorkoutPlan, style: Theme.of(context).textTheme.headlineSmall, ), subtitle: Text( @@ -473,7 +494,9 @@ class _DashboardWorkoutWidgetState extends State { trailing: _hasContent ? Tooltip( message: AppLocalizations.of(context).toggleDetails, - child: _showDetail ? const Icon(Icons.info) : const Icon(Icons.info_outline), + child: _showDetail + ? const Icon(Icons.info) + : const Icon(Icons.info_outline), ) : const SizedBox(), onTap: () { diff --git a/lib/widgets/exercises/exercises.dart b/lib/widgets/exercises/exercises.dart index bfd515bf8..57c2e5c6d 100644 --- a/lib/widgets/exercises/exercises.dart +++ b/lib/widgets/exercises/exercises.dart @@ -33,16 +33,23 @@ import 'package:wger/widgets/exercises/images.dart'; import 'package:wger/widgets/exercises/list_tile.dart'; import 'package:wger/widgets/exercises/videos.dart'; -class ExerciseDetail extends StatelessWidget { +class ExerciseDetail extends StatefulWidget { final Exercise _exerciseBase; - late Translation _exercise; static const PADDING = 9.0; - ExerciseDetail(this._exerciseBase); + const ExerciseDetail(this._exerciseBase); + + @override + State createState() => _ExerciseDetailState(); +} + +class _ExerciseDetailState extends State { + late Translation _exercise; @override Widget build(BuildContext context) { - _exercise = _exerciseBase.getExercise(Localizations.localeOf(context).languageCode); + _exercise = widget._exerciseBase + .getExercise(Localizations.localeOf(context).languageCode); return SingleChildScrollView( child: Column( @@ -79,7 +86,7 @@ class ExerciseDetail extends StatelessWidget { List getVariations(BuildContext context) { final List out = []; - if (_exerciseBase.variationId == null) { + if (widget._exerciseBase.variationId == null) { return out; } @@ -89,14 +96,14 @@ class ExerciseDetail extends StatelessWidget { )); Provider.of(context, listen: false) .findExercisesByVariationId( - _exerciseBase.variationId!, - exerciseBaseIdToExclude: _exerciseBase.id, + widget._exerciseBase.variationId!, + exerciseBaseIdToExclude: widget._exerciseBase.id, ) .forEach((element) { out.add(ExerciseListTile(exerciseBase: element)); }); - out.add(const SizedBox(height: PADDING)); + out.add(const SizedBox(height: ExerciseDetail.PADDING)); return out; } @@ -110,7 +117,7 @@ class ExerciseDetail extends StatelessWidget { for (final e in _exercise.notes) { out.add(Text(e.comment)); } - out.add(const SizedBox(height: PADDING)); + out.add(const SizedBox(height: ExerciseDetail.PADDING)); } return out; @@ -128,20 +135,22 @@ class ExerciseDetail extends StatelessWidget { children: [ Expanded( child: Padding( - padding: const EdgeInsets.symmetric(horizontal: PADDING), + padding: + const EdgeInsets.symmetric(horizontal: ExerciseDetail.PADDING), child: MuscleWidget( - muscles: _exerciseBase.muscles, - musclesSecondary: _exerciseBase.musclesSecondary, + muscles: widget._exerciseBase.muscles, + musclesSecondary: widget._exerciseBase.musclesSecondary, isFront: true, ), ), ), Expanded( child: Padding( - padding: const EdgeInsets.symmetric(horizontal: PADDING), + padding: + const EdgeInsets.symmetric(horizontal: ExerciseDetail.PADDING), child: MuscleWidget( - muscles: _exerciseBase.muscles, - musclesSecondary: _exerciseBase.musclesSecondary, + muscles: widget._exerciseBase.muscles, + musclesSecondary: widget._exerciseBase.musclesSecondary, isFront: false, ), ), @@ -154,22 +163,23 @@ class ExerciseDetail extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ const MuscleColorHelper(main: true), - ..._exerciseBase.muscles.map((e) => Text(e.nameTranslated(context))), + ...widget._exerciseBase.muscles + .map((e) => Text(e.nameTranslated(context))), ], ), ); - out.add(const SizedBox(height: PADDING)); + out.add(const SizedBox(height: ExerciseDetail.PADDING)); out.add( Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const MuscleColorHelper(main: false), - ..._exerciseBase.musclesSecondary.map((e) => Text(e.name)), + ...widget._exerciseBase.musclesSecondary.map((e) => Text(e.name)), ], ), ); - out.add(const SizedBox(height: PADDING)); + out.add(const SizedBox(height: ExerciseDetail.PADDING)); return out; } @@ -188,9 +198,9 @@ class ExerciseDetail extends StatelessWidget { List getImages() { // TODO: add carousel for the other images final List out = []; - if (_exerciseBase.getMainImage != null) { - out.add(ExerciseImageWidget(image: _exerciseBase.getMainImage)); - out.add(const SizedBox(height: PADDING)); + if (widget._exerciseBase.getMainImage != null) { + out.add(ExerciseImageWidget(image: widget._exerciseBase.getMainImage)); + out.add(const SizedBox(height: ExerciseDetail.PADDING)); } return out; @@ -204,14 +214,15 @@ class ExerciseDetail extends StatelessWidget { Padding( padding: const EdgeInsets.symmetric(horizontal: 4), child: Chip( - label: Text(getTranslation(_exerciseBase.category!.name, context)), + label: Text( + getTranslation(widget._exerciseBase.category!.name, context)), padding: EdgeInsets.zero, backgroundColor: theme.splashColor, ), ), ); - if (_exerciseBase.equipment.isNotEmpty) { - _exerciseBase.equipment + if (widget._exerciseBase.equipment.isNotEmpty) { + widget._exerciseBase.equipment .map((e) => Padding( padding: const EdgeInsets.symmetric(horizontal: 4), child: Chip( @@ -222,19 +233,21 @@ class ExerciseDetail extends StatelessWidget { )) .forEach((element) => out.add(element)); } - out.add(const SizedBox(height: PADDING)); + out.add(const SizedBox(height: ExerciseDetail.PADDING)); return Row(children: [...out]); } List getVideos() { // TODO: add carousel for the other videos final List out = []; - if (_exerciseBase.videos.isNotEmpty && !isDesktop) { - _exerciseBase.videos.map((v) => ExerciseVideoWidget(video: v)).forEach((element) { + if (widget._exerciseBase.videos.isNotEmpty && !isDesktop) { + widget._exerciseBase.videos + .map((v) => ExerciseVideoWidget(video: v)) + .forEach((element) { out.add(element); }); - out.add(const SizedBox(height: PADDING)); + out.add(const SizedBox(height: ExerciseDetail.PADDING)); } return out; } @@ -247,7 +260,7 @@ class ExerciseDetail extends StatelessWidget { _exercise.aliases.map((e) => e.alias).toList().join(', '), ), )); - out.add(const SizedBox(height: PADDING)); + out.add(const SizedBox(height: ExerciseDetail.PADDING)); } return out; @@ -331,7 +344,8 @@ class MuscleWidget extends StatelessWidget { this.isFront = true, }) { this.muscles = muscles.where((m) => m.isFront == isFront).toList(); - this.musclesSecondary = musclesSecondary.where((m) => m.isFront == isFront).toList(); + this.musclesSecondary = + musclesSecondary.where((m) => m.isFront == isFront).toList(); } @override @@ -341,7 +355,8 @@ class MuscleWidget extends StatelessWidget { return Stack( children: [ SvgPicture.asset('assets/images/muscles/$background.svg'), - ...muscles.map((m) => SvgPicture.asset('assets/images/muscles/main/muscle-${m.id}.svg')), + ...muscles.map((m) => + SvgPicture.asset('assets/images/muscles/main/muscle-${m.id}.svg')), ...musclesSecondary.map((m) => SvgPicture.asset( 'assets/images/muscles/secondary/muscle-${m.id}.svg', )), diff --git a/lib/widgets/exercises/filter_modal.dart b/lib/widgets/exercises/filter_modal.dart index 9ac88ad04..bc00c529f 100644 --- a/lib/widgets/exercises/filter_modal.dart +++ b/lib/widgets/exercises/filter_modal.dart @@ -25,7 +25,8 @@ class ExerciseFilterModalBody extends StatefulWidget { const ExerciseFilterModalBody({super.key}); @override - _ExerciseFilterModalBodyState createState() => _ExerciseFilterModalBodyState(); + _ExerciseFilterModalBodyState createState() => + _ExerciseFilterModalBodyState(); } class _ExerciseFilterModalBodyState extends State { @@ -57,11 +58,9 @@ class _ExerciseFilterModalBodyState extends State { backgroundColor: Colors.transparent, isExpanded: filterCategory.isExpanded, headerBuilder: (context, isExpanded) { - return Container( - child: Text( - filterCategory.title, - style: theme.textTheme.headlineSmall, - ), + return Text( + filterCategory.title, + style: theme.textTheme.headlineSmall, ); }, body: Column( @@ -71,8 +70,10 @@ class _ExerciseFilterModalBodyState extends State { value: currentEntry.value, onChanged: (_) { setState(() { - filterCategory.items.update(currentEntry.key, (value) => !value); - Provider.of(context, listen: false).setFilters(filters); + filterCategory.items + .update(currentEntry.key, (value) => !value); + Provider.of(context, listen: false) + .setFilters(filters); }); }, ); diff --git a/lib/widgets/exercises/filter_row.dart b/lib/widgets/exercises/filter_row.dart index 807c530f0..d3341867a 100644 --- a/lib/widgets/exercises/filter_row.dart +++ b/lib/widgets/exercises/filter_row.dart @@ -42,7 +42,8 @@ class _FilterRowState extends State { ..addListener(() { final provider = Provider.of(context, listen: false); if (provider.filters!.searchTerm != _exerciseNameController.text) { - provider.setFilters(provider.filters!.copyWith(searchTerm: _exerciseNameController.text)); + provider.setFilters(provider.filters! + .copyWith(searchTerm: _exerciseNameController.text)); } }); } @@ -87,7 +88,8 @@ class _FilterRowState extends State { return [ PopupMenuItem( value: ExerciseMoreOption.ADD_EXERCISE, - child: Text(AppLocalizations.of(context).contributeExercise), + child: + Text(AppLocalizations.of(context).contributeExercise), ), ]; }, @@ -97,7 +99,8 @@ class _FilterRowState extends State { onSelected: (ExerciseMoreOption selectedOption) { switch (selectedOption) { case ExerciseMoreOption.ADD_EXERCISE: - Navigator.of(context).pushNamed(AddExerciseScreen.routeName); + Navigator.of(context) + .pushNamed(AddExerciseScreen.routeName); break; } }, diff --git a/lib/widgets/exercises/forms.dart b/lib/widgets/exercises/forms.dart index d07577280..4fd085c75 100644 --- a/lib/widgets/exercises/forms.dart +++ b/lib/widgets/exercises/forms.dart @@ -21,35 +21,28 @@ import 'package:flutter/material.dart'; /// Input widget for exercise category objects /// /// Can be used with a Setting or a Log object -class ExerciseCategoryInputWidget extends StatefulWidget { - late final String _title; - late final Function _callback; - late final List _entries; - late final Function _getDisplayName; - late final Function? _validator; - late final Key? _key; - ExerciseCategoryInputWidget({ - Key? key, - required String title, - required List entries, - required Function callback, - required Function displayName, - Function? validator, - }) { - _key = key; - _entries = entries; - _title = title; - _callback = callback; - _getDisplayName = displayName; - _validator = validator; - } +class ExerciseCategoryInputWidget extends StatefulWidget { + final String title; + final Function callback; + final List entries; + final Function displayName; + final Function? validator; + const ExerciseCategoryInputWidget( + {required this.title, + required this.callback, + required this.entries, + required this.displayName, + this.validator, + super.key}); @override - _ExerciseCategoryInputWidgetState createState() => _ExerciseCategoryInputWidgetState(); + State createState() => + _ExerciseCategoryInputWidgetState(); } -class _ExerciseCategoryInputWidgetState extends State { +class _ExerciseCategoryInputWidgetState + extends State { @override Widget build(BuildContext context) { T? selectedEntry; @@ -60,7 +53,7 @@ class _ExerciseCategoryInputWidgetState extends State extends State>((value) { + items: widget.entries.map>((value) { return DropdownMenuItem( key: Key(value.id.toString()), value: value, - child: Text(widget._getDisplayName(value)), + child: Text(widget.displayName(value)), ); }).toList(), ), diff --git a/lib/widgets/exercises/list_tile.dart b/lib/widgets/exercises/list_tile.dart index f1574b451..5c4b62606 100644 --- a/lib/widgets/exercises/list_tile.dart +++ b/lib/widgets/exercises/list_tile.dart @@ -49,7 +49,9 @@ class ExerciseListTile extends StatelessWidget { ), ), title: Text( - exerciseBase.getExercise(Localizations.localeOf(context).languageCode).name, + exerciseBase + .getExercise(Localizations.localeOf(context).languageCode) + .name, //style: theme.textTheme.titleLarge, overflow: TextOverflow.ellipsis, maxLines: 2, @@ -58,7 +60,8 @@ class ExerciseListTile extends StatelessWidget { '${getTranslation(exerciseBase.category!.name, context)} / ${exerciseBase.equipment.map((e) => getTranslation(e.name, context)).toList().join(', ')}', ), onTap: () { - Navigator.pushNamed(context, ExerciseDetailScreen.routeName, arguments: exerciseBase); + Navigator.pushNamed(context, ExerciseDetailScreen.routeName, + arguments: exerciseBase); }, ); } diff --git a/lib/widgets/exercises/videos.dart b/lib/widgets/exercises/videos.dart index aad1ebd91..6169cc30b 100644 --- a/lib/widgets/exercises/videos.dart +++ b/lib/widgets/exercises/videos.dart @@ -35,7 +35,8 @@ class _ExerciseVideoWidgetState extends State { @override void initState() { super.initState(); - _controller = VideoPlayerController.network(widget.video.url); + final url = Uri.parse(widget.video.url); + _controller = VideoPlayerController.networkUrl(url); _controller.addListener(() { setState(() {}); }); diff --git a/lib/widgets/gallery/forms.dart b/lib/widgets/gallery/forms.dart index 218a12976..32d8b340f 100644 --- a/lib/widgets/gallery/forms.dart +++ b/lib/widgets/gallery/forms.dart @@ -118,7 +118,8 @@ class _ImageFormState extends State { _showPicker(ImageSource.camera); }, leading: const Icon(Icons.photo_camera), - title: Text(AppLocalizations.of(context).takePicture), + title: + Text(AppLocalizations.of(context).takePicture), ), ListTile( onTap: () { diff --git a/lib/widgets/gallery/overview.dart b/lib/widgets/gallery/overview.dart index 0301b2c9a..ed0871583 100644 --- a/lib/widgets/gallery/overview.dart +++ b/lib/widgets/gallery/overview.dart @@ -58,15 +58,18 @@ class Gallery extends StatelessWidget { child: Column( children: [ Text( - DateFormat.yMd(Localizations.localeOf(context).languageCode) + DateFormat.yMd(Localizations.localeOf(context) + .languageCode) .format(currentImage.date), - style: Theme.of(context).textTheme.headlineSmall, + style: + Theme.of(context).textTheme.headlineSmall, ), Expanded( child: Image.network(currentImage.url!), ), Padding( - padding: const EdgeInsets.symmetric(vertical: 8), + padding: + const EdgeInsets.symmetric(vertical: 8), child: Text(currentImage.description), ), Row( @@ -107,7 +110,8 @@ class Gallery extends StatelessWidget { }, child: FadeInImage( key: Key('image-${currentImage.id}'), - placeholder: const AssetImage('assets/images/placeholder.png'), + placeholder: + const AssetImage('assets/images/placeholder.png'), image: NetworkImage(currentImage.url!), fit: BoxFit.cover, ), diff --git a/lib/widgets/measurements/categories.dart b/lib/widgets/measurements/categories.dart index 32abf49e6..255e20a82 100644 --- a/lib/widgets/measurements/categories.dart +++ b/lib/widgets/measurements/categories.dart @@ -33,7 +33,8 @@ class CategoriesList extends StatelessWidget { child: ListView.builder( padding: const EdgeInsets.all(10.0), itemCount: provider.categories.length, - itemBuilder: (context, index) => CategoriesCard(provider.categories[index]), + itemBuilder: (context, index) => + CategoriesCard(provider.categories[index]), ), ); } diff --git a/lib/widgets/measurements/categories_card.dart b/lib/widgets/measurements/categories_card.dart index 7e835a5bb..870decec9 100644 --- a/lib/widgets/measurements/categories_card.dart +++ b/lib/widgets/measurements/categories_card.dart @@ -17,7 +17,9 @@ class CategoriesCard extends StatelessWidget { @override Widget build(BuildContext context) { final (entriesAll, entries7dAvg) = sensibleRange( - currentCategory.entries.map((e) => MeasurementChartEntry(e.value, e.date)).toList(), + currentCategory.entries + .map((e) => MeasurementChartEntry(e.value, e.date)) + .toList(), ); return Card( diff --git a/lib/widgets/measurements/charts.dart b/lib/widgets/measurements/charts.dart index f92a959db..6209f341e 100644 --- a/lib/widgets/measurements/charts.dart +++ b/lib/widgets/measurements/charts.dart @@ -46,7 +46,9 @@ class MeasurementOverallChangeWidget extends StatelessWidget { } String weightUnit(bool isMetric, BuildContext context) { - return isMetric ? AppLocalizations.of(context).kg : AppLocalizations.of(context).lb; + return isMetric + ? AppLocalizations.of(context).kg + : AppLocalizations.of(context).lb; } class MeasurementChartWidgetFl extends StatefulWidget { @@ -57,7 +59,8 @@ class MeasurementChartWidgetFl extends StatefulWidget { const MeasurementChartWidgetFl(this._entries, this._unit, {this.avgs}); @override - State createState() => _MeasurementChartWidgetFlState(); + State createState() => + _MeasurementChartWidgetFlState(); } class _MeasurementChartWidgetFlState extends State { @@ -75,12 +78,15 @@ class _MeasurementChartWidgetFlState extends State { LineTouchData tooltipData() { return LineTouchData( touchTooltipData: LineTouchTooltipData( - getTooltipColor: (touchedSpot) => Theme.of(context).colorScheme.primaryContainer, + getTooltipColor: (touchedSpot) => + Theme.of(context).colorScheme.primaryContainer, getTooltipItems: (touchedSpots) { return touchedSpots.map((touchedSpot) { - final DateTime date = DateTime.fromMillisecondsSinceEpoch(touchedSpot.x.toInt()); + final DateTime date = + DateTime.fromMillisecondsSinceEpoch(touchedSpot.x.toInt()); final dateStr = - DateFormat.Md(Localizations.localeOf(context).languageCode).format(date); + DateFormat.Md(Localizations.localeOf(context).languageCode) + .format(date); return LineTooltipItem( '$dateStr: ${touchedSpot.y.toStringAsFixed(1)} ${widget._unit}', @@ -101,10 +107,14 @@ class _MeasurementChartWidgetFlState extends State { // horizontalInterval: 1, // verticalInterval: 1, getDrawingHorizontalLine: (value) { - return FlLine(color: Theme.of(context).colorScheme.primaryContainer, strokeWidth: 1); + return FlLine( + color: Theme.of(context).colorScheme.primaryContainer, + strokeWidth: 1); }, getDrawingVerticalLine: (value) { - return FlLine(color: Theme.of(context).colorScheme.primaryContainer, strokeWidth: 1); + return FlLine( + color: Theme.of(context).colorScheme.primaryContainer, + strokeWidth: 1); }, ), titlesData: FlTitlesData( @@ -125,16 +135,19 @@ class _MeasurementChartWidgetFlState extends State { if (value == meta.min || value == meta.max) { return const Text(''); } - final DateTime date = DateTime.fromMillisecondsSinceEpoch(value.toInt()); + final DateTime date = + DateTime.fromMillisecondsSinceEpoch(value.toInt()); // if we go across years, show years in the ticks. otherwise leave them out if (DateTime.fromMillisecondsSinceEpoch(meta.min.toInt()).year != DateTime.fromMillisecondsSinceEpoch(meta.max.toInt()).year) { return Text( - DateFormat.yMd(Localizations.localeOf(context).languageCode).format(date), + DateFormat.yMd(Localizations.localeOf(context).languageCode) + .format(date), ); } return Text( - DateFormat.Md(Localizations.localeOf(context).languageCode).format(date), + DateFormat.Md(Localizations.localeOf(context).languageCode) + .format(date), ); }, interval: widget._entries.isNotEmpty @@ -164,7 +177,8 @@ class _MeasurementChartWidgetFlState extends State { ), borderData: FlBorderData( show: true, - border: Border.all(color: Theme.of(context).colorScheme.primaryContainer), + border: + Border.all(color: Theme.of(context).colorScheme.primaryContainer), ), lineBarsData: [ LineChartBarData( diff --git a/lib/widgets/measurements/entries.dart b/lib/widgets/measurements/entries.dart index 68a3db34b..43a349394 100644 --- a/lib/widgets/measurements/entries.dart +++ b/lib/widgets/measurements/entries.dart @@ -36,10 +36,12 @@ class EntriesList extends StatelessWidget { @override Widget build(BuildContext context) { - final plan = Provider.of(context, listen: false).currentPlan; + final plan = + Provider.of(context, listen: false).currentPlan; - final entriesAll = - _category.entries.map((e) => MeasurementChartEntry(e.value, e.date)).toList(); + final entriesAll = _category.entries + .map((e) => MeasurementChartEntry(e.value, e.date)) + .toList(); final entries7dAvg = moving7dAverage(entriesAll); return Column(children: [ @@ -58,7 +60,8 @@ class EntriesList extends StatelessWidget { itemCount: _category.entries.length, itemBuilder: (context, index) { final currentEntry = _category.entries[index]; - final provider = Provider.of(context, listen: false); + final provider = + Provider.of(context, listen: false); return Card( child: ListTile( @@ -98,7 +101,8 @@ class EntriesList extends StatelessWidget { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( - AppLocalizations.of(context).successfullyDeleted, + AppLocalizations.of(context) + .successfullyDeleted, textAlign: TextAlign.center, ), ), diff --git a/lib/widgets/measurements/forms.dart b/lib/widgets/measurements/forms.dart index 57fa0d370..a975da22f 100644 --- a/lib/widgets/measurements/forms.dart +++ b/lib/widgets/measurements/forms.dart @@ -59,7 +59,8 @@ class MeasurementCategoryForm extends StatelessWidget { TextFormField( decoration: InputDecoration( labelText: AppLocalizations.of(context).name, - helperText: AppLocalizations.of(context).measurementCategoriesHelpText, + helperText: + AppLocalizations.of(context).measurementCategoriesHelpText, ), controller: nameController, onSaved: (newValue) { @@ -77,7 +78,8 @@ class MeasurementCategoryForm extends StatelessWidget { TextFormField( decoration: InputDecoration( labelText: AppLocalizations.of(context).unit, - helperText: AppLocalizations.of(context).measurementEntriesHelpText, + helperText: + AppLocalizations.of(context).measurementEntriesHelpText, ), controller: unitController, onSaved: (newValue) { @@ -174,7 +176,8 @@ class MeasurementEntryForm extends StatelessWidget { @override Widget build(BuildContext context) { - final measurementProvider = Provider.of(context, listen: false); + final measurementProvider = + Provider.of(context, listen: false); final measurementCategory = measurementProvider.categories.firstWhere( (category) => category.id == _categoryId, ); @@ -184,7 +187,8 @@ class MeasurementEntryForm extends StatelessWidget { child: Column( children: [ TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).date), + decoration: + InputDecoration(labelText: AppLocalizations.of(context).date), readOnly: true, // Hide text cursor controller: _dateController, onTap: () async { @@ -225,7 +229,8 @@ class MeasurementEntryForm extends StatelessWidget { decoration: InputDecoration( labelText: AppLocalizations.of(context).value, suffixIcon: Text(measurementCategory.unit), - suffixIconConstraints: const BoxConstraints(minWidth: 0, minHeight: 0), + suffixIconConstraints: + const BoxConstraints(minWidth: 0, minHeight: 0), ), controller: _valueController, keyboardType: TextInputType.number, @@ -246,7 +251,8 @@ class MeasurementEntryForm extends StatelessWidget { ), // Value TextFormField( - decoration: InputDecoration(labelText: AppLocalizations.of(context).notes), + decoration: + InputDecoration(labelText: AppLocalizations.of(context).notes), controller: _notesController, onSaved: (newValue) { _entryData['notes'] = newValue; @@ -254,8 +260,10 @@ class MeasurementEntryForm extends StatelessWidget { validator: (value) { const minLength = 0; const maxLength = 100; - if (value!.isNotEmpty && (value.length < minLength || value.length > maxLength)) { - return AppLocalizations.of(context).enterCharacters(minLength, maxLength); + if (value!.isNotEmpty && + (value.length < minLength || value.length > maxLength)) { + return AppLocalizations.of(context) + .enterCharacters(minLength, maxLength); } return null; }, diff --git a/lib/widgets/measurements/helpers.dart b/lib/widgets/measurements/helpers.dart index 000b72e37..7fe7f4868 100644 --- a/lib/widgets/measurements/helpers.dart +++ b/lib/widgets/measurements/helpers.dart @@ -21,7 +21,8 @@ List getOverviewWidgets( height: 220, child: MeasurementChartWidgetFl(raw, unit, avgs: avg), ), - if (avg.isNotEmpty) MeasurementOverallChangeWidget(avg.first, avg.last, unit), + if (avg.isNotEmpty) + MeasurementOverallChangeWidget(avg.first, avg.last, unit), const SizedBox(height: 8), ]; } @@ -35,7 +36,8 @@ List getOverviewWidgetsSeries( BuildContext context, ) { final monthAgo = DateTime.now().subtract(const Duration(days: 30)); - final showPlan = plan != null && entriesAll.any((e) => e.date.isAfter(plan.creationDate)); + final showPlan = + plan != null && entriesAll.any((e) => e.date.isAfter(plan.creationDate)); return [ ...getOverviewWidgets( @@ -47,7 +49,8 @@ List getOverviewWidgetsSeries( ), if (showPlan) ...getOverviewWidgets( - AppLocalizations.of(context).chartDuringPlanTitle(name, plan.description), + AppLocalizations.of(context) + .chartDuringPlanTitle(name, plan.description), entriesAll.where((e) => e.date.isAfter(plan.creationDate)).toList(), entries7dAvg.where((e) => e.date.isAfter(plan.creationDate)).toList(), unit, @@ -58,13 +61,15 @@ List getOverviewWidgetsSeries( // then let's show a separate chart just focusing on the last 30 days, // if there is data for it. if (entriesAll.isNotEmpty && - entriesAll.first.date.isBefore(entriesAll.last.date.subtract(const Duration(days: 75))) && + entriesAll.first.date.isBefore( + entriesAll.last.date.subtract(const Duration(days: 75))) && (plan == null || (showPlan && entriesAll .firstWhere((e) => e.date.isAfter(plan.creationDate)) .date - .isBefore(entriesAll.last.date.subtract(const Duration(days: 30))))) && + .isBefore(entriesAll.last.date + .subtract(const Duration(days: 30))))) && entriesAll.any((e) => e.date.isAfter(monthAgo))) ...getOverviewWidgets( AppLocalizations.of(context).chart30DaysTitle(name), @@ -77,8 +82,14 @@ List getOverviewWidgetsSeries( Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Indicator(color: Theme.of(context).colorScheme.primary, text: AppLocalizations.of(context).indicatorRaw, isSquare: true), - Indicator(color: Theme.of(context).colorScheme.tertiary, text: AppLocalizations.of(context).indicatorAvg, isSquare: true), + Indicator( + color: Theme.of(context).colorScheme.primary, + text: AppLocalizations.of(context).indicatorRaw, + isSquare: true), + Indicator( + color: Theme.of(context).colorScheme.tertiary, + text: AppLocalizations.of(context).indicatorAvg, + isSquare: true), ], ), ]; diff --git a/lib/widgets/nutrition/charts.dart b/lib/widgets/nutrition/charts.dart index c429f0a83..836c61261 100644 --- a/lib/widgets/nutrition/charts.dart +++ b/lib/widgets/nutrition/charts.dart @@ -98,8 +98,10 @@ class FlNutritionalPlanGoalWidget extends StatelessWidget { // if none goes over, 100% means fill all available space final maxVal = [ 1.0, - if (goals.energy != null && goals.energy! > 0) today.energy / goals.energy!, - if (goals.protein != null && goals.protein! > 0) today.protein / goals.protein!, + if (goals.energy != null && goals.energy! > 0) + today.energy / goals.energy!, + if (goals.protein != null && goals.protein! > 0) + today.protein / goals.protein!, if (goals.carbohydrates != null && goals.carbohydrates! > 0) today.carbohydrates / goals.carbohydrates!, if (goals.fat != null && goals.fat! > 0) today.fat / goals.fat!, @@ -190,7 +192,8 @@ class FlNutritionalPlanPieChartWidget extends StatefulWidget { State createState() => FlNutritionalPlanPieChartState(); } -class FlNutritionalPlanPieChartState extends State { +class FlNutritionalPlanPieChartState + extends State { int touchedIndex = -1; @override @@ -212,7 +215,8 @@ class FlNutritionalPlanPieChartState extends State createState() => NutritionalDiaryChartWidgetFlState(); } -class NutritionalDiaryChartWidgetFlState extends State { +class NutritionalDiaryChartWidgetFlState + extends State { Widget bottomTitles(double value, TitleMeta meta) { const style = TextStyle(fontSize: 10); final String text = switch (value.toInt()) { @@ -289,7 +294,7 @@ class NutritionalDiaryChartWidgetFlState extends State '', }; return SideTitleWidget( - axisSide: meta.axisSide, + meta: meta, child: Text(text, style: style), ); } @@ -299,7 +304,7 @@ class NutritionalDiaryChartWidgetFlState extends State { _ => '', }; return SideTitleWidget( - axisSide: meta.axisSide, + meta: meta, child: Text(text, style: const TextStyle(fontSize: 10)), ); } Widget leftTitles(double value, TitleMeta meta) => SideTitleWidget( - axisSide: meta.axisSide, + meta: meta, child: Text( AppLocalizations.of(context).percentValue(value.toStringAsFixed(0)), style: const TextStyle(fontSize: 10), @@ -547,7 +553,9 @@ class MealDiaryBarChartWidgetState extends State { barsSpace: barsSpace, barRods: [ BarChartRodData( - toY: widget._logged.energy / widget._planned.energy * 100, + toY: widget._logged.energy / + widget._planned.energy * + 100, color: LIST_OF_COLORS3.first, width: barsWidth, ), @@ -558,7 +566,9 @@ class MealDiaryBarChartWidgetState extends State { barsSpace: barsSpace, barRods: [ BarChartRodData( - toY: widget._logged.protein / widget._planned.protein * 100, + toY: widget._logged.protein / + widget._planned.protein * + 100, color: LIST_OF_COLORS3.first, width: barsWidth, ), @@ -569,7 +579,9 @@ class MealDiaryBarChartWidgetState extends State { barsSpace: barsSpace, barRods: [ BarChartRodData( - toY: widget._logged.carbohydrates / widget._planned.carbohydrates * 100, + toY: widget._logged.carbohydrates / + widget._planned.carbohydrates * + 100, color: LIST_OF_COLORS3.first, width: barsWidth, ), diff --git a/lib/widgets/nutrition/forms.dart b/lib/widgets/nutrition/forms.dart index 1ab0c67d1..0034d2c84 100644 --- a/lib/widgets/nutrition/forms.dart +++ b/lib/widgets/nutrition/forms.dart @@ -43,7 +43,8 @@ class MealForm extends StatelessWidget { final _nameController = TextEditingController(); MealForm(this._planId, [meal]) { - _meal = meal ?? Meal(plan: _planId, time: TimeOfDay.fromDateTime(DateTime.now())); + _meal = meal ?? + Meal(plan: _planId, time: TimeOfDay.fromDateTime(DateTime.now())); _timeController.text = timeToString(_meal.time)!; _nameController.text = _meal.name; } @@ -58,7 +59,8 @@ class MealForm extends StatelessWidget { children: [ TextFormField( key: const Key('field-time'), - decoration: InputDecoration(labelText: AppLocalizations.of(context).time), + decoration: + InputDecoration(labelText: AppLocalizations.of(context).time), controller: _timeController, onTap: () async { // Stop keyboard from appearing @@ -80,7 +82,8 @@ class MealForm extends StatelessWidget { TextFormField( maxLength: 25, key: const Key('field-name'), - decoration: InputDecoration(labelText: AppLocalizations.of(context).name), + decoration: + InputDecoration(labelText: AppLocalizations.of(context).name), controller: _nameController, onSaved: (newValue) { _meal.name = newValue as String; @@ -131,7 +134,8 @@ Widget MealItemForm( recent: recent.map((e) => Log.fromMealItem(e, 0, e.mealId)).toList(), onSave: (BuildContext context, MealItem mealItem, DateTime? dt) { mealItem.mealId = meal.id!; - Provider.of(context, listen: false).addMealItem(mealItem, meal); + Provider.of(context, listen: false) + .addMealItem(mealItem, meal); }, barcode: barcode ?? '', test: test ?? false, @@ -241,8 +245,9 @@ class IngredientFormState extends State { Widget build(BuildContext context) { final String unit = AppLocalizations.of(context).g; final queryLower = _searchQuery.toLowerCase(); - final suggestions = - widget.recent.where((e) => e.ingredient.name.toLowerCase().contains(queryLower)).toList(); + final suggestions = widget.recent + .where((e) => e.ingredient.name.toLowerCase().contains(queryLower)) + .toList(); return Container( margin: const EdgeInsets.all(20), child: Form( @@ -347,7 +352,8 @@ class IngredientFormState extends State { ), ], ), - if (ingredientIdController.text.isNotEmpty && _amountController.text.isNotEmpty) + if (ingredientIdController.text.isNotEmpty && + _amountController.text.isNotEmpty) Padding( padding: const EdgeInsets.all(8.0), child: Column( @@ -398,7 +404,8 @@ class IngredientFormState extends State { return; } _form.currentState!.save(); - _mealItem.ingredientId = int.parse(_ingredientIdController.text); + _mealItem.ingredientId = + int.parse(_ingredientIdController.text); try { var date = DateTime.parse(_dateController.text); @@ -498,211 +505,196 @@ enum GoalType { } class PlanForm extends StatefulWidget { - late NutritionalPlan _plan; + final NutritionalPlan? plan; - PlanForm([NutritionalPlan? plan]) { - _plan = plan ?? NutritionalPlan.empty(); - } + const PlanForm({ this.plan, Key? key}) : super(key: key); @override State createState() => _PlanFormState(); } class _PlanFormState extends State { - final _form = GlobalKey(); - - bool _onlyLogging = true; - GoalType _goalType = GoalType.meals; - - final _descriptionController = TextEditingController(); - final TextEditingController colorController = TextEditingController(); - - GoalType? selectedGoal; + final _formKey = GlobalKey(); + late final TextEditingController _descriptionController; + late bool? _onlyLogging; + late GoalType? _goalType; @override void initState() { super.initState(); - - _onlyLogging = widget._plan.onlyLogging; - _descriptionController.text = widget._plan.description; - if (widget._plan.hasAnyAdvancedGoals) { - _goalType = GoalType.advanced; - } else if (widget._plan.hasAnyGoals) { - _goalType = GoalType.basic; - } else { - _goalType = GoalType.meals; - } + _onlyLogging = widget.plan?.onlyLogging; + _descriptionController = + TextEditingController(text: widget.plan?.description); + _goalType = widget.plan != null ? _determineGoalType(widget.plan!) : null; } @override void dispose() { _descriptionController.dispose(); - colorController.dispose(); super.dispose(); } + GoalType _determineGoalType(NutritionalPlan plan) { + if (plan.hasAnyAdvancedGoals) { + return GoalType.advanced; + } else if (plan.hasAnyGoals) { + return GoalType.basic; + } else { + return GoalType.meals; + } + } + + void _saveForm() async { + if (!_formKey.currentState!.validate()) return; + + _formKey.currentState!.save(); + + try { + final provider = + Provider.of(context, listen: false); + + if (widget.plan != null && widget.plan?.id != null) { + await provider.editPlan(widget.plan!); + if (mounted) Navigator.pop(context); + } else { + final newPlan = await provider.addPlan(widget.plan!); + if (mounted) { + Navigator.pushReplacementNamed( + context, + NutritionalPlanScreen.routeName, + arguments: newPlan, + ); + } + } + } catch (error) { + if (mounted) showErrorDialog(error, context); + } + } + @override Widget build(BuildContext context) { return Form( - key: _form, + key: _formKey, child: ListView( children: [ - // Description - TextFormField( - key: const Key('field-description'), - decoration: InputDecoration( - labelText: AppLocalizations.of(context).description, - ), - controller: _descriptionController, - onSaved: (newValue) { - widget._plan.description = newValue!; - }, - ), - SwitchListTile( - title: Text(AppLocalizations.of(context).onlyLogging), - subtitle: Text(AppLocalizations.of(context).onlyLoggingHelpText), - value: _onlyLogging, - onChanged: (value) { - setState(() { - _onlyLogging = !_onlyLogging; - }); - widget._plan.onlyLogging = value; - }, - ), - Row( - children: [ - Text( - AppLocalizations.of(context).goalMacro, - style: Theme.of(context).textTheme.titleMedium, - ), - const SizedBox(width: 8), - Expanded( - child: DropdownButtonFormField( - value: _goalType, - items: GoalType.values - .map( - (e) => DropdownMenuItem( - value: e, - child: Text(e.getI18nLabel(context)), - ), - ) - .toList(), - onChanged: (GoalType? g) { - setState(() { - if (g == null) { - return; - } - switch (g) { - case GoalType.meals: - widget._plan.goalEnergy = null; - widget._plan.goalProtein = null; - widget._plan.goalCarbohydrates = null; - widget._plan.goalFat = null; - widget._plan.goalFiber = null; - case GoalType.basic: - widget._plan.goalFiber = null; - break; - default: - break; - } - _goalType = g; - }); - }, - ), - ), - ], - ), + _buildDescriptionField(context), + _buildOnlyLoggingSwitch(context), + _buildGoalTypeDropdown(context), if (_goalType == GoalType.basic || _goalType == GoalType.advanced) - Column( - children: [ - GoalMacros( - val: widget._plan.goalEnergy?.toString(), - label: AppLocalizations.of(context).goalEnergy, - suffix: AppLocalizations.of(context).kcal, - onSave: (double value) => widget._plan.goalEnergy = value, - key: const Key('field-goal-energy'), - ), - GoalMacros( - val: widget._plan.goalProtein?.toString(), - label: AppLocalizations.of(context).goalProtein, - suffix: AppLocalizations.of(context).g, - onSave: (double value) => widget._plan.goalProtein = value, - key: const Key('field-goal-protein'), - ), - GoalMacros( - val: widget._plan.goalCarbohydrates?.toString(), - label: AppLocalizations.of(context).goalCarbohydrates, - suffix: AppLocalizations.of(context).g, - onSave: (double value) => widget._plan.goalCarbohydrates = value, - key: const Key('field-goal-carbohydrates'), - ), - GoalMacros( - val: widget._plan.goalFat?.toString(), - label: AppLocalizations.of(context).goalFat, - suffix: AppLocalizations.of(context).g, - onSave: (double value) => widget._plan.goalFat = value, - key: const Key('field-goal-fat'), - ), - ], - ), + _buildGoalFields(context), + if (_goalType == GoalType.advanced) _buildFiberGoalField(context), + _buildSaveButton(context), + ], + ), + ); + } - if (_goalType == GoalType.advanced) - GoalMacros( - val: widget._plan.goalFiber?.toString(), - label: AppLocalizations.of(context).goalFiber, - suffix: AppLocalizations.of(context).g, - onSave: (double value) => widget._plan.goalFiber = value, - key: const Key('field-goal-fiber'), - ), - ElevatedButton( - key: const Key(SUBMIT_BUTTON_KEY_NAME), - child: Text(AppLocalizations.of(context).save), - onPressed: () async { - // Validate and save the current values to the plan - final isValid = _form.currentState!.validate(); - if (!isValid) { - return; - } - _form.currentState!.save(); - - // Save to DB - try { - if (widget._plan.id != null) { - await Provider.of( - context, - listen: false, - ).editPlan(widget._plan); - if (context.mounted) { - Navigator.of(context).pop(); - } - } else { - widget._plan = await Provider.of( - context, - listen: false, - ).addPlan(widget._plan); - if (context.mounted) { - Navigator.of(context).pushReplacementNamed( - NutritionalPlanScreen.routeName, - arguments: widget._plan, - ); - } - } + Widget _buildDescriptionField(BuildContext context) { + return TextFormField( + key: const Key('field-description'), + controller: _descriptionController, + decoration: + InputDecoration(labelText: AppLocalizations.of(context).description), + onSaved: (value) => widget.plan?.description = value ?? '', + ); + } - // Saving was successful, reset the data - _descriptionController.clear(); - } on WgerHttpException catch (error) { - if (context.mounted) { - showHttpExceptionErrorDialog(error, context); - } - } catch (error) { - if (context.mounted) { - showErrorDialog(error, context); - } + Widget _buildOnlyLoggingSwitch(BuildContext context) { + return SwitchListTile( + title: Text(AppLocalizations.of(context).onlyLogging), + subtitle: Text(AppLocalizations.of(context).onlyLoggingHelpText), + value: _onlyLogging ?? false, + onChanged: (value) => setState(() { + _onlyLogging = value; + widget.plan?.onlyLogging = value; + }), + ); + } + + Widget _buildGoalTypeDropdown(BuildContext context) { + return Row( + children: [ + Text(AppLocalizations.of(context).goalMacro, + style: Theme.of(context).textTheme.titleMedium), + const SizedBox(width: 8), + Expanded( + child: DropdownButtonFormField( + value: _goalType, + items: GoalType.values.map((goal) { + return DropdownMenuItem( + value: goal, + child: Text(goal.getI18nLabel(context)), + ); + }).toList(), + onChanged: (goal) => setState(() { + _goalType = goal!; + if (widget.plan != null && goal == GoalType.meals) { + widget.plan?.goalCarbohydrates = null; + widget.plan?.goalEnergy = null; + widget.plan?.goalFat = null; + widget.plan?.goalProtein = null; + widget.plan?.goalFiber = null; + } else if (widget.plan?.goalFiber != null && + goal == GoalType.basic) { + widget.plan!.goalFiber = null; } - }, + }), ), - ], - ), + ), + ], + ); + } + + Widget _buildGoalFields(BuildContext context) { + return Column( + children: [ + GoalMacros( + val: widget.plan?.goalEnergy?.toString(), + label: AppLocalizations.of(context).goalEnergy, + suffix: AppLocalizations.of(context).kcal, + onSave: (value) => widget.plan?.goalEnergy = value, + key: const Key('field-goal-energy'), + ), + GoalMacros( + val: widget.plan?.goalProtein?.toString(), + label: AppLocalizations.of(context).goalProtein, + suffix: AppLocalizations.of(context).g, + onSave: (value) => widget.plan?.goalProtein = value, + key: const Key('field-goal-protein'), + ), + GoalMacros( + val: widget.plan?.goalCarbohydrates?.toString(), + label: AppLocalizations.of(context).goalCarbohydrates, + suffix: AppLocalizations.of(context).g, + onSave: (value) => widget.plan?.goalCarbohydrates = value, + key: const Key('field-goal-carbohydrates'), + ), + GoalMacros( + val: widget.plan?.goalFat?.toString(), + label: AppLocalizations.of(context).goalFat, + suffix: AppLocalizations.of(context).g, + onSave: (value) => widget.plan?.goalFat = value, + key: const Key('field-goal-fat'), + ), + ], + ); + } + + Widget _buildFiberGoalField(BuildContext context) { + return GoalMacros( + val: widget.plan?.goalFiber?.toString(), + label: AppLocalizations.of(context).goalFiber, + suffix: AppLocalizations.of(context).g, + onSave: (value) => widget.plan?.goalFiber = value, + key: const Key('field-goal-fiber'), + ); + } + + Widget _buildSaveButton(BuildContext context) { + return ElevatedButton( + key: const Key('submit-button'), + onPressed: _saveForm, + child: Text(AppLocalizations.of(context).save), ); } } diff --git a/lib/widgets/nutrition/helpers.dart b/lib/widgets/nutrition/helpers.dart index b60661fb4..d9737f24a 100644 --- a/lib/widgets/nutrition/helpers.dart +++ b/lib/widgets/nutrition/helpers.dart @@ -33,10 +33,13 @@ List getNutritionColumnNames(BuildContext context) => [ AppLocalizations.of(context).fat, ]; -List getNutritionalValues(NutritionalValues values, BuildContext context) => [ +List getNutritionalValues( + NutritionalValues values, BuildContext context) => + [ AppLocalizations.of(context).kcalValue(values.energy.toStringAsFixed(0)), AppLocalizations.of(context).gValue(values.protein.toStringAsFixed(0)), - AppLocalizations.of(context).gValue(values.carbohydrates.toStringAsFixed(0)), + AppLocalizations.of(context) + .gValue(values.carbohydrates.toStringAsFixed(0)), AppLocalizations.of(context).gValue(values.fat.toStringAsFixed(0)), ]; @@ -77,33 +80,40 @@ Row getNutritionRow(BuildContext context, List children) { String getShortNutritionValues(NutritionalValues values, BuildContext context) { final loc = AppLocalizations.of(context); - final e = '${loc.energyShort} ${loc.kcalValue(values.energy.toStringAsFixed(0))}'; - final p = '${loc.proteinShort} ${loc.gValue(values.protein.toStringAsFixed(0))}'; - final c = '${loc.carbohydratesShort} ${loc.gValue(values.carbohydrates.toStringAsFixed(0))}'; + final e = + '${loc.energyShort} ${loc.kcalValue(values.energy.toStringAsFixed(0))}'; + final p = + '${loc.proteinShort} ${loc.gValue(values.protein.toStringAsFixed(0))}'; + final c = + '${loc.carbohydratesShort} ${loc.gValue(values.carbohydrates.toStringAsFixed(0))}'; final f = '${loc.fatShort} ${loc.gValue(values.fat.toStringAsFixed(0))}'; return '$e / $p / $c / $f'; } String getKcalConsumed(Meal meal, BuildContext context) { - final consumed = - meal.diaryEntriesToday.map((e) => e.nutritionalValues.energy).fold(0.0, (a, b) => a + b); + final consumed = meal.diaryEntriesToday + .map((e) => e.nutritionalValues.energy) + .fold(0.0, (a, b) => a + b); return AppLocalizations.of(context).kcalValue(consumed.toStringAsFixed(0)); } String getKcalConsumedVsPlanned(Meal meal, BuildContext context) { final planned = meal.plannedNutritionalValues.energy; - final consumed = - meal.diaryEntriesToday.map((e) => e.nutritionalValues.energy).fold(0.0, (a, b) => a + b); + final consumed = meal.diaryEntriesToday + .map((e) => e.nutritionalValues.energy) + .fold(0.0, (a, b) => a + b); final loc = AppLocalizations.of(context); return '${consumed.toStringAsFixed(0)} / ${planned.toStringAsFixed(0)} ${loc.kcal}'; } -void showIngredientDetails(BuildContext context, int id, {void Function()? select}) { +void showIngredientDetails(BuildContext context, int id, + {void Function()? select}) { showDialog( context: context, builder: (context) => FutureBuilder( - future: Provider.of(context, listen: false).fetchIngredient(id), + future: Provider.of(context, listen: false) + .fetchIngredient(id), builder: (BuildContext context, AsyncSnapshot snapshot) { return IngredientDetails(snapshot, onSelect: select); }, diff --git a/lib/widgets/nutrition/ingredient_dialogs.dart b/lib/widgets/nutrition/ingredient_dialogs.dart index b5fcde098..6d5f47c23 100644 --- a/lib/widgets/nutrition/ingredient_dialogs.dart +++ b/lib/widgets/nutrition/ingredient_dialogs.dart @@ -51,7 +51,8 @@ class IngredientDetails extends StatelessWidget { ), if (ingredient?.image?.image != null) ingredientImage(ingredient!.image!.image, context), - if (!snapshot.hasData && !snapshot.hasError) const CircularProgressIndicator(), + if (!snapshot.hasData && !snapshot.hasError) + const CircularProgressIndicator(), if (snapshot.hasData) ConstrainedBox( constraints: const BoxConstraints(minWidth: 400), @@ -68,7 +69,8 @@ class IngredientDetails extends StatelessWidget { padding: const EdgeInsets.only(top: 12), child: InkWell( child: Text('Source: ${source!}'), - onTap: () => launchURL(ingredient!.licenseObjectURl!, context), + onTap: () => + launchURL(ingredient!.licenseObjectURl!, context), ), ), ], @@ -140,22 +142,25 @@ class IngredientScanResultDialog extends StatelessWidget { 'Ingredient lookup error: ${snapshot.error ?? 'unknown error'}', style: const TextStyle(color: Colors.red), ), - if (snapshot.connectionState == ConnectionState.done && ingredient == null) + if (snapshot.connectionState == ConnectionState.done && + ingredient == null) Padding( padding: const EdgeInsets.only(bottom: 8.0), child: Text( - AppLocalizations.of(context).productNotFoundDescription(barcode), + AppLocalizations.of(context) + .productNotFoundDescription(barcode), ), ), if (ingredient != null) Padding( padding: const EdgeInsets.only(bottom: 8.0), - child: - Text(AppLocalizations.of(context).productFoundDescription(ingredient.name)), + child: Text(AppLocalizations.of(context) + .productFoundDescription(ingredient.name)), ), if (ingredient?.image?.image != null) ingredientImage(ingredient!.image!.image, context), - if (snapshot.connectionState != ConnectionState.done && !snapshot.hasError) + if (snapshot.connectionState != ConnectionState.done && + !snapshot.hasError) const CircularProgressIndicator(), if (goals != null) ConstrainedBox( @@ -173,7 +178,8 @@ class IngredientScanResultDialog extends StatelessWidget { padding: const EdgeInsets.only(top: 12), child: InkWell( child: Text('Source: ${source!}'), - onTap: () => launchURL(ingredient!.licenseObjectURl!, context), + onTap: () => + launchURL(ingredient!.licenseObjectURl!, context), ), ), ], diff --git a/lib/widgets/nutrition/macro_nutrients_table.dart b/lib/widgets/nutrition/macro_nutrients_table.dart index c5bc5c4b4..0bb45dfed 100644 --- a/lib/widgets/nutrition/macro_nutrients_table.dart +++ b/lib/widgets/nutrition/macro_nutrients_table.dart @@ -30,22 +30,28 @@ class MacronutrientsTable extends StatelessWidget { ), ); - TableRow macroRow(int indent, bool g, String title, double? Function(NutritionalGoals ng) get) { + TableRow macroRow(int indent, bool g, String title, + double? Function(NutritionalGoals ng) get) { final goal = get(nutritionalGoals); final pct = get(plannedValuesPercentage); - final perkg = nutritionalGoalsGperKg == null ? null : get(nutritionalGoalsGperKg!); + final perkg = + nutritionalGoalsGperKg == null ? null : get(nutritionalGoalsGperKg!); final valFn = g ? loc.gValue : loc.kcalValue; return TableRow( children: [ Padding( - padding: EdgeInsets.symmetric(vertical: tablePadding, horizontal: indent * 12), + padding: EdgeInsets.symmetric( + vertical: tablePadding, horizontal: indent * 12), child: Text(title), ), - Text(goal != null ? valFn(goal.toStringAsFixed(0)) : '', textAlign: TextAlign.right), - Text(pct != null ? pct.toStringAsFixed(1) : '', textAlign: TextAlign.right), + Text(goal != null ? valFn(goal.toStringAsFixed(0)) : '', + textAlign: TextAlign.right), + Text(pct != null ? pct.toStringAsFixed(1) : '', + textAlign: TextAlign.right), if (showGperKg) - Text(perkg != null ? perkg.toStringAsFixed(1) : '', textAlign: TextAlign.right), + Text(perkg != null ? perkg.toStringAsFixed(1) : '', + textAlign: TextAlign.right), ], ); } @@ -70,10 +76,13 @@ class MacronutrientsTable extends StatelessWidget { ), macroRow(0, false, loc.energy, (NutritionalGoals ng) => ng.energy), macroRow(0, true, loc.protein, (NutritionalGoals ng) => ng.protein), - macroRow(0, true, loc.carbohydrates, (NutritionalGoals ng) => ng.carbohydrates), - macroRow(1, true, loc.sugars, (NutritionalGoals ng) => ng.carbohydratesSugar), + macroRow(0, true, loc.carbohydrates, + (NutritionalGoals ng) => ng.carbohydrates), + macroRow(1, true, loc.sugars, + (NutritionalGoals ng) => ng.carbohydratesSugar), macroRow(0, true, loc.fat, (NutritionalGoals ng) => ng.fat), - macroRow(1, true, loc.saturatedFat, (NutritionalGoals ng) => ng.fatSaturated), + macroRow(1, true, loc.saturatedFat, + (NutritionalGoals ng) => ng.fatSaturated), macroRow(0, true, loc.fiber, (NutritionalGoals ng) => ng.fiber), macroRow(0, true, loc.sodium, (NutritionalGoals ng) => ng.sodium), ], diff --git a/lib/widgets/nutrition/meal.dart b/lib/widgets/nutrition/meal.dart index d79370616..893798f53 100644 --- a/lib/widgets/nutrition/meal.dart +++ b/lib/widgets/nutrition/meal.dart @@ -160,11 +160,14 @@ class _MealWidgetState extends State { ], ), ), - if (_viewMode == viewMode.withIngredients || _viewMode == viewMode.withAllDetails) + if (_viewMode == viewMode.withIngredients || + _viewMode == viewMode.withAllDetails) const Divider(), - if (_viewMode == viewMode.withIngredients || _viewMode == viewMode.withAllDetails) + if (_viewMode == viewMode.withIngredients || + _viewMode == viewMode.withAllDetails) const DiaryheaderTile(), - if (_viewMode == viewMode.withIngredients || _viewMode == viewMode.withAllDetails) + if (_viewMode == viewMode.withIngredients || + _viewMode == viewMode.withAllDetails) if (widget._meal.mealItems.isEmpty && widget._meal.isRealMeal) NutritionTile( title: Text( @@ -173,17 +176,20 @@ class _MealWidgetState extends State { ), ) else - ...widget._meal.mealItems - .map((item) => MealItemEditableFullTile(item, _viewMode, _editing)), - if (_viewMode == viewMode.withIngredients || _viewMode == viewMode.withAllDetails) + ...widget._meal.mealItems.map((item) => + MealItemEditableFullTile(item, _viewMode, _editing)), + if (_viewMode == viewMode.withIngredients || + _viewMode == viewMode.withAllDetails) const Divider(), - if (_viewMode == viewMode.withIngredients || _viewMode == viewMode.withAllDetails) + if (_viewMode == viewMode.withIngredients || + _viewMode == viewMode.withAllDetails) NutritionTile( vPadding: 0, leading: const Text('total'), title: getNutritionRow( context, - muted(getNutritionalValues(widget._meal.plannedNutritionalValues, context)), + muted(getNutritionalValues( + widget._meal.plannedNutritionalValues, context)), ), ), if (_viewMode == viewMode.withAllDetails) @@ -250,7 +256,8 @@ class MealItemEditableFullTile extends StatelessWidget { ), subtitle: (_viewMode != viewMode.withAllDetails && !_editing) ? null - : getNutritionRow(context, muted(getNutritionalValues(values, context))), + : getNutritionRow( + context, muted(getNutritionalValues(values, context))), trailing: _editing ? IconButton( icon: const Icon(Icons.delete, size: ICON_SIZE_SMALL), @@ -258,7 +265,8 @@ class MealItemEditableFullTile extends StatelessWidget { iconSize: ICON_SIZE_SMALL, onPressed: () { // Delete the meal item - Provider.of(context, listen: false).deleteMealItem(_item); + Provider.of(context, listen: false) + .deleteMealItem(_item); // and inform the user ScaffoldMessenger.of(context).showSnackBar( @@ -305,7 +313,8 @@ class MealHeader extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ ListTile( - contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 8), title: Row(children: [ Expanded( child: Column( @@ -352,7 +361,9 @@ class MealHeader extends StatelessWidget { if (_meal.isRealMeal && !readOnly) const SizedBox(width: 5), if (_meal.isRealMeal && !readOnly) IconButton( - icon: _editing ? const Icon(Icons.done) : const Icon(Icons.edit), + icon: _editing + ? const Icon(Icons.done) + : const Icon(Icons.edit), tooltip: _editing ? AppLocalizations.of(context).done : AppLocalizations.of(context).edit, @@ -361,7 +372,8 @@ class MealHeader extends StatelessWidget { }, ), if (_meal.isRealMeal) const SizedBox(width: 5), - if (_meal.isRealMeal) const SvgIcon(icon: SvgIconData('assets/icons/meal-diary.svg')), + if (_meal.isRealMeal) + const SvgIcon(icon: SvgIconData('assets/icons/meal-diary.svg')), ], ), onTap: _meal.isRealMeal diff --git a/lib/widgets/nutrition/nutrition_tiles.dart b/lib/widgets/nutrition/nutrition_tiles.dart index 304ef9f38..0da3fa7ce 100644 --- a/lib/widgets/nutrition/nutrition_tiles.dart +++ b/lib/widgets/nutrition/nutrition_tiles.dart @@ -47,7 +47,9 @@ class DiaryheaderTile extends StatelessWidget { @override Widget build(BuildContext context) { - return NutritionTile(title: getNutritionRow(context, muted(getNutritionColumnNames(context)))); + return NutritionTile( + title: + getNutritionRow(context, muted(getNutritionColumnNames(context)))); } } @@ -66,7 +68,8 @@ class DiaryEntryTile extends StatelessWidget { Widget build(BuildContext context) { return NutritionTile( leading: Text( - DateFormat.Hm(Localizations.localeOf(context).languageCode).format(diaryEntry.datetime), + DateFormat.Hm(Localizations.localeOf(context).languageCode) + .format(diaryEntry.datetime), style: const TextStyle(fontWeight: FontWeight.bold), ), title: Text( diff --git a/lib/widgets/nutrition/nutritional_diary_detail.dart b/lib/widgets/nutrition/nutritional_diary_detail.dart index 93a9ae203..c246de1fc 100644 --- a/lib/widgets/nutrition/nutritional_diary_detail.dart +++ b/lib/widgets/nutrition/nutritional_diary_detail.dart @@ -62,7 +62,8 @@ class NutritionalDiaryDetailWidget extends StatelessWidget { const SizedBox(height: 15), const DiaryheaderTile(), ...logs.map( - (e) => DiaryEntryTile(diaryEntry: e, nutritionalPlan: _nutritionalPlan), + (e) => + DiaryEntryTile(diaryEntry: e, nutritionalPlan: _nutritionalPlan), ), ], ); @@ -93,17 +94,22 @@ class NutritionDiaryTable extends StatelessWidget { ), ); - TableRow macroRow(int indent, bool g, String title, double Function(NutritionalValues nv) get) { + TableRow macroRow(int indent, bool g, String title, + double Function(NutritionalValues nv) get) { final valFn = g ? loc.gValue : loc.kcalValue; return TableRow( children: [ Padding( - padding: EdgeInsets.symmetric(vertical: tablePadding, horizontal: indent * 12), + padding: EdgeInsets.symmetric( + vertical: tablePadding, horizontal: indent * 12), child: Text(title), ), - Text(valFn(get(planned).toStringAsFixed(0)), textAlign: TextAlign.right), - Text(valFn(get(logged).toStringAsFixed(0)), textAlign: TextAlign.right), - Text((get(logged) - get(planned)).toStringAsFixed(0), textAlign: TextAlign.right), + Text(valFn(get(planned).toStringAsFixed(0)), + textAlign: TextAlign.right), + Text(valFn(get(logged).toStringAsFixed(0)), + textAlign: TextAlign.right), + Text((get(logged) - get(planned)).toStringAsFixed(0), + textAlign: TextAlign.right), ], ); } @@ -111,7 +117,8 @@ class NutritionDiaryTable extends StatelessWidget { return Table( defaultVerticalAlignment: TableCellVerticalAlignment.middle, border: TableBorder( - horizontalInside: BorderSide(width: 1, color: Theme.of(context).colorScheme.outline), + horizontalInside: + BorderSide(width: 1, color: Theme.of(context).colorScheme.outline), ), columnWidths: const {0: FractionColumnWidth(0.4)}, children: [ @@ -123,10 +130,13 @@ class NutritionDiaryTable extends StatelessWidget { ]), macroRow(0, false, loc.energy, (NutritionalValues nv) => nv.energy), macroRow(0, true, loc.protein, (NutritionalValues nv) => nv.protein), - macroRow(0, true, loc.carbohydrates, (NutritionalValues nv) => nv.carbohydrates), - macroRow(1, true, loc.sugars, (NutritionalValues nv) => nv.carbohydratesSugar), + macroRow(0, true, loc.carbohydrates, + (NutritionalValues nv) => nv.carbohydrates), + macroRow(1, true, loc.sugars, + (NutritionalValues nv) => nv.carbohydratesSugar), macroRow(0, true, loc.fat, (NutritionalValues nv) => nv.fat), - macroRow(1, true, loc.saturatedFat, (NutritionalValues nv) => nv.fatSaturated), + macroRow(1, true, loc.saturatedFat, + (NutritionalValues nv) => nv.fatSaturated), macroRow(0, true, loc.fiber, (NutritionalValues nv) => nv.fiber), macroRow(0, true, loc.sodium, (NutritionalValues nv) => nv.sodium), ], diff --git a/lib/widgets/nutrition/nutritional_diary_table.dart b/lib/widgets/nutrition/nutritional_diary_table.dart index ec7dddc87..27fd8d6df 100644 --- a/lib/widgets/nutrition/nutritional_diary_table.dart +++ b/lib/widgets/nutrition/nutritional_diary_table.dart @@ -31,7 +31,8 @@ class NutritionalDiaryTable extends StatelessWidget { children: [ nutrionalDiaryHeader(context, goals), ...plan.logEntriesValues.entries - .map((entry) => nutritionDiaryEntry(context, goals, entry.key, entry.value)) + .map((entry) => + nutritionDiaryEntry(context, goals, entry.key, entry.value)) .toList() .reversed, ], @@ -84,8 +85,12 @@ class NutritionalDiaryTable extends StatelessWidget { ), children: [ Text( - style: Theme.of(context).textTheme.titleMedium?.copyWith(color: LIST_OF_COLORS3.first), - DateFormat.Md(Localizations.localeOf(context).languageCode).format(date), + style: Theme.of(context) + .textTheme + .titleMedium + ?.copyWith(color: LIST_OF_COLORS3.first), + DateFormat.Md(Localizations.localeOf(context).languageCode) + .format(date), ), Text( style: Theme.of(context).textTheme.titleMedium, diff --git a/lib/widgets/nutrition/nutritional_plan_detail.dart b/lib/widgets/nutrition/nutritional_plan_detail.dart index 63e69e534..855a689b0 100644 --- a/lib/widgets/nutrition/nutritional_plan_detail.dart +++ b/lib/widgets/nutrition/nutritional_plan_detail.dart @@ -35,9 +35,11 @@ class NutritionalPlanDetailWidget extends StatelessWidget { Widget build(BuildContext context) { final nutritionalGoals = _nutritionalPlan.nutritionalGoals; final lastWeightEntry = - Provider.of(context, listen: false).getNewestEntry(); - final nutritionalGoalsGperKg = - lastWeightEntry != null ? nutritionalGoals / lastWeightEntry.weight.toDouble() : null; + Provider.of(context, listen: false) + .getNewestEntry(); + final nutritionalGoalsGperKg = lastWeightEntry != null + ? nutritionalGoals / lastWeightEntry.weight.toDouble() + : null; return SliverList( delegate: SliverChildListDelegate( @@ -68,7 +70,8 @@ class NutritionalPlanDetailWidget extends StatelessWidget { Container( padding: const EdgeInsets.all(15), height: 220, - child: FlNutritionalPlanPieChartWidget(nutritionalGoals.toValues()), + child: + FlNutritionalPlanPieChartWidget(nutritionalGoals.toValues()), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 10), diff --git a/lib/widgets/nutrition/nutritional_plans_list.dart b/lib/widgets/nutrition/nutritional_plans_list.dart index d1a6a48e0..4e37ee033 100644 --- a/lib/widgets/nutrition/nutritional_plans_list.dart +++ b/lib/widgets/nutrition/nutritional_plans_list.dart @@ -71,29 +71,35 @@ class NutritionalPlansList extends StatelessWidget { actions: [ TextButton( child: Text( - MaterialLocalizations.of(context).cancelButtonLabel, + MaterialLocalizations.of(context) + .cancelButtonLabel, ), - onPressed: () => Navigator.of(contextDialog).pop(), + onPressed: () => + Navigator.of(contextDialog).pop(), ), TextButton( child: Text( AppLocalizations.of(context).delete, style: TextStyle( - color: Theme.of(context).colorScheme.error, + color: + Theme.of(context).colorScheme.error, ), ), onPressed: () { // Confirmed, delete the plan - _nutritionProvider.deletePlan(currentPlan.id!); + _nutritionProvider + .deletePlan(currentPlan.id!); // Close the popup Navigator.of(contextDialog).pop(); // and inform the user - ScaffoldMessenger.of(context).showSnackBar( + ScaffoldMessenger.of(context) + .showSnackBar( SnackBar( content: Text( - AppLocalizations.of(context).successfullyDeleted, + AppLocalizations.of(context) + .successfullyDeleted, textAlign: TextAlign.center, ), ), diff --git a/lib/widgets/nutrition/widgets.dart b/lib/widgets/nutrition/widgets.dart index 00afff5b4..bff098cdd 100644 --- a/lib/widgets/nutrition/widgets.dart +++ b/lib/widgets/nutrition/widgets.dart @@ -92,8 +92,8 @@ class _IngredientTypeaheadState extends State { Future readerscan(BuildContext context) async { try { - final code = await Navigator.of(context) - .push(MaterialPageRoute(builder: (context) => const ScanReader())); + final code = await Navigator.of(context).push( + MaterialPageRoute(builder: (context) => const ScanReader())); if (code == null) { return ''; } @@ -132,28 +132,36 @@ class _IngredientTypeaheadState extends State { decoration: InputDecoration( prefixIcon: const Icon(Icons.search), labelText: AppLocalizations.of(context).searchIngredient, - suffixIcon: (widget.showScanner && !isDesktop) ? scanButton() : null, + suffixIcon: + (widget.showScanner && !isDesktop) ? scanButton() : null, ), ); }, suggestionsCallback: (pattern) { // don't do search if user has already loaded a specific item - if (pattern == '' || widget._ingredientIdController.text.isNotEmpty) { + if (pattern == '' || + widget._ingredientIdController.text.isNotEmpty) { return null; } - return Provider.of(context, listen: false).searchIngredient( + return Provider.of(context, listen: false) + .searchIngredient( pattern, languageCode: Localizations.localeOf(context).languageCode, searchEnglish: _searchEnglish, ); }, itemBuilder: (context, suggestion) { - final url = context.read().baseProvider.auth.serverUrl; + final url = context + .read() + .baseProvider + .auth + .serverUrl; return ListTile( leading: suggestion.data.image != null ? CircleAvatar( - backgroundImage: NetworkImage(url! + suggestion.data.image!), + backgroundImage: + NetworkImage(url! + suggestion.data.image!), ) : const CircleIconAvatar( Icon(Icons.image, color: Colors.grey), @@ -167,7 +175,8 @@ class _IngredientTypeaheadState extends State { context, suggestion.data.id, select: () { - widget.selectIngredient(suggestion.data.id, suggestion.value, null); + widget.selectIngredient( + suggestion.data.id, suggestion.value, null); }, ); }, @@ -175,14 +184,16 @@ class _IngredientTypeaheadState extends State { ); }, transitionBuilder: (context, animation, child) => FadeTransition( - opacity: CurvedAnimation(parent: animation, curve: Curves.fastOutSlowIn), + opacity: + CurvedAnimation(parent: animation, curve: Curves.fastOutSlowIn), child: child, ), onSelected: (suggestion) { widget.selectIngredient(suggestion.data.id, suggestion.value, null); }, ), - if (Localizations.localeOf(context).languageCode != LANGUAGE_SHORT_ENGLISH) + if (Localizations.localeOf(context).languageCode != + LANGUAGE_SHORT_ENGLISH) SwitchListTile( title: Text(AppLocalizations.of(context).searchNamesInEnglish), value: _searchEnglish, @@ -219,8 +230,10 @@ class _IngredientTypeaheadState extends State { builder: (context) => FutureBuilder( future: Provider.of(context, listen: false) .searchIngredientWithCode(barcode), - builder: (BuildContext context, AsyncSnapshot snapshot) { - return IngredientScanResultDialog(snapshot, barcode, widget.selectIngredient); + builder: + (BuildContext context, AsyncSnapshot snapshot) { + return IngredientScanResultDialog( + snapshot, barcode, widget.selectIngredient); }, ), ); diff --git a/lib/widgets/user/forms.dart b/lib/widgets/user/forms.dart index b11ded4b7..efd162937 100644 --- a/lib/widgets/user/forms.dart +++ b/lib/widgets/user/forms.dart @@ -109,13 +109,16 @@ class _UserProfileFormState extends State { // Verify await context.read().verifyEmail(); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - AppLocalizations.of(context).verifiedEmailInfo(widget._profile.email), + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + AppLocalizations.of(context) + .verifiedEmailInfo(widget._profile.email), + ), ), - ), - ); + ); + } }, child: Text(AppLocalizations.of(context).verify), ), diff --git a/lib/widgets/weight/forms.dart b/lib/widgets/weight/forms.dart index 343a0cf87..8505b89a4 100644 --- a/lib/widgets/weight/forms.dart +++ b/lib/widgets/weight/forms.dart @@ -35,7 +35,8 @@ class WeightForm extends StatelessWidget { WeightForm([WeightEntry? weightEntry]) { _weightEntry = weightEntry ?? WeightEntry(date: DateTime.now()); - weightController.text = _weightEntry.weight == 0 ? '' : _weightEntry.weight.toString(); + weightController.text = + _weightEntry.weight == 0 ? '' : _weightEntry.weight.toString(); dateController.text = toDate(_weightEntry.date)!; } @@ -73,7 +74,8 @@ class WeightForm extends StatelessWidget { } // if the date is known, don't allow it - return Provider.of(context, listen: false).findByDate(day) == + return Provider.of(context, listen: false) + .findByDate(day) == null; }, ); @@ -100,7 +102,8 @@ class WeightForm extends StatelessWidget { icon: const FaIcon(FontAwesomeIcons.circleMinus), onPressed: () { try { - final num newValue = num.parse(weightController.text) - 1; + final num newValue = + num.parse(weightController.text) - 1; weightController.text = newValue.toString(); } on FormatException {} }, @@ -110,7 +113,8 @@ class WeightForm extends StatelessWidget { icon: const FaIcon(FontAwesomeIcons.minus), onPressed: () { try { - final num newValue = num.parse(weightController.text) - 0.1; + final num newValue = + num.parse(weightController.text) - 0.1; weightController.text = newValue.toStringAsFixed(1); } on FormatException {} }, @@ -125,7 +129,8 @@ class WeightForm extends StatelessWidget { icon: const FaIcon(FontAwesomeIcons.plus), onPressed: () { try { - final num newValue = num.parse(weightController.text) + 0.1; + final num newValue = + num.parse(weightController.text) + 0.1; weightController.text = newValue.toStringAsFixed(1); } on FormatException {} }, @@ -135,7 +140,8 @@ class WeightForm extends StatelessWidget { icon: const FaIcon(FontAwesomeIcons.circlePlus), onPressed: () { try { - final num newValue = num.parse(weightController.text) + 1; + final num newValue = + num.parse(weightController.text) + 1; weightController.text = newValue.toString(); } on FormatException {} }, @@ -172,7 +178,8 @@ class WeightForm extends StatelessWidget { // Save the entry on the server try { - final provider = Provider.of(context, listen: false); + final provider = + Provider.of(context, listen: false); _weightEntry.id == null ? await provider.addEntry(_weightEntry) : await provider.editEntry(_weightEntry); diff --git a/lib/widgets/weight/weight_overview.dart b/lib/widgets/weight/weight_overview.dart index 93fedfd28..719e0a759 100644 --- a/lib/widgets/weight/weight_overview.dart +++ b/lib/widgets/weight/weight_overview.dart @@ -37,9 +37,12 @@ class WeightOverview extends StatelessWidget { @override Widget build(BuildContext context) { final profile = context.read().profile; - final plan = Provider.of(context, listen: false).currentPlan; + final plan = + Provider.of(context, listen: false).currentPlan; - final entriesAll = _provider.items.map((e) => MeasurementChartEntry(e.weight, e.date)).toList(); + final entriesAll = _provider.items + .map((e) => MeasurementChartEntry(e.weight, e.date)) + .toList(); final entries7dAvg = moving7dAverage(entriesAll); final unit = weightUnit(profile!.isMetric, context); @@ -78,7 +81,8 @@ class WeightOverview extends StatelessWidget { final currentEntry = _provider.items[index]; return Card( child: ListTile( - title: Text('${currentEntry.weight} ${weightUnit(profile.isMetric, context)}'), + title: Text( + '${currentEntry.weight} ${weightUnit(profile.isMetric, context)}'), subtitle: Text( DateFormat.yMd( Localizations.localeOf(context).languageCode, @@ -109,7 +113,8 @@ class WeightOverview extends StatelessWidget { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( - AppLocalizations.of(context).successfullyDeleted, + AppLocalizations.of(context) + .successfullyDeleted, textAlign: TextAlign.center, ), ), diff --git a/lib/widgets/workouts/app_bar.dart b/lib/widgets/workouts/app_bar.dart index eb1b7563f..8ab24a5a6 100644 --- a/lib/widgets/workouts/app_bar.dart +++ b/lib/widgets/workouts/app_bar.dart @@ -26,7 +26,8 @@ enum _WorkoutAppBarOptions { contribute, } -class WorkoutOverviewAppBar extends StatelessWidget implements PreferredSizeWidget { +class WorkoutOverviewAppBar extends StatelessWidget + implements PreferredSizeWidget { const WorkoutOverviewAppBar(); @override Widget build(BuildContext context) { diff --git a/lib/widgets/workouts/charts.dart b/lib/widgets/workouts/charts.dart index e41e249ab..4b6274289 100644 --- a/lib/widgets/workouts/charts.dart +++ b/lib/widgets/workouts/charts.dart @@ -25,9 +25,8 @@ import 'package:wger/helpers/colors.dart'; class LogChartWidgetFl extends StatefulWidget { final Map _data; - final DateTime _currentDate; - const LogChartWidgetFl(this._data, this._currentDate); + const LogChartWidgetFl(this._data); @override State createState() => _LogChartWidgetFlState(); @@ -50,7 +49,8 @@ class _LogChartWidgetFlState extends State { touchTooltipData: LineTouchTooltipData( getTooltipItems: (touchedSpots) { return touchedSpots.map((touchedSpot) { - final reps = widget._data['chart_data'][touchedSpot.barIndex].first['reps']; + final reps = + widget._data['chart_data'][touchedSpot.barIndex].first['reps']; return LineTooltipItem( '$reps × ${touchedSpot.y} kg', @@ -63,7 +63,8 @@ class _LogChartWidgetFlState extends State { } LineChartData mainData() { - final colors = generateChartColors(widget._data['chart_data'].length).iterator; + final colors = + generateChartColors(widget._data['chart_data'].length).iterator; return LineChartData( lineTouchData: tooltipData(), @@ -95,9 +96,11 @@ class _LogChartWidgetFlState extends State { return const Text(''); } - final DateTime date = DateTime.fromMillisecondsSinceEpoch(value.toInt()); + final DateTime date = + DateTime.fromMillisecondsSinceEpoch(value.toInt()); return Text( - DateFormat.yMd(Localizations.localeOf(context).languageCode).format(date), + DateFormat.yMd(Localizations.localeOf(context).languageCode) + .format(date), ); }, interval: chartGetInterval( @@ -127,7 +130,9 @@ class _LogChartWidgetFlState extends State { spots: [ ...e.map( (entry) => FlSpot( - DateTime.parse(entry['date']).millisecondsSinceEpoch.toDouble(), + DateTime.parse(entry['date']) + .millisecondsSinceEpoch + .toDouble(), double.parse(entry['weight']), ), ), diff --git a/lib/widgets/workouts/day.dart b/lib/widgets/workouts/day.dart index 82ab108a2..c494c05db 100644 --- a/lib/widgets/workouts/day.dart +++ b/lib/widgets/workouts/day.dart @@ -77,7 +77,9 @@ class SettingWidget extends StatelessWidget { }, ), title: Text( - setting.exerciseObj.getExercise(Localizations.localeOf(context).languageCode).name, + setting.exerciseObj + .getExercise(Localizations.localeOf(context).languageCode) + .name, ), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -127,7 +129,8 @@ class _WorkoutDayWidgetState extends State { iconSize: ICON_SIZE_SMALL, tooltip: AppLocalizations.of(context).delete, onPressed: () { - Provider.of(context, listen: false).deleteSet(set); + Provider.of(context, listen: false) + .deleteSet(set); }, ), Expanded( @@ -250,7 +253,8 @@ class _WorkoutDayWidgetState extends State { ).reorderSets(_sets, startIndex); }, children: [ - for (var i = 0; i < widget._day.sets.length; i++) getSetRow(widget._day.sets[i], i), + for (var i = 0; i < widget._day.sets.length; i++) + getSetRow(widget._day.sets[i], i), ], ), ], @@ -282,7 +286,8 @@ class DayHeader extends StatelessWidget { style: Theme.of(context).textTheme.headlineSmall, overflow: TextOverflow.ellipsis, ), - subtitle: Text(_day.getDaysTextTranslated(Localizations.localeOf(context).languageCode)), + subtitle: Text(_day + .getDaysTextTranslated(Localizations.localeOf(context).languageCode)), leading: const Icon(Icons.play_arrow), minLeadingWidth: 8, trailing: Row(mainAxisSize: MainAxisSize.min, children: [ @@ -290,7 +295,9 @@ class DayHeader extends StatelessWidget { const SizedBox(width: 10), IconButton( icon: _editing ? const Icon(Icons.done) : const Icon(Icons.edit), - tooltip: _editing ? AppLocalizations.of(context).done : AppLocalizations.of(context).edit, + tooltip: _editing + ? AppLocalizations.of(context).done + : AppLocalizations.of(context).edit, onPressed: () { _toggle(); }, diff --git a/lib/widgets/workouts/forms.dart b/lib/widgets/workouts/forms.dart index 7609172dc..711bf6dfd 100644 --- a/lib/widgets/workouts/forms.dart +++ b/lib/widgets/workouts/forms.dart @@ -41,7 +41,8 @@ class WorkoutForm extends StatelessWidget { WorkoutForm(this._plan); final TextEditingController workoutNameController = TextEditingController(); - final TextEditingController workoutDescriptionController = TextEditingController(); + final TextEditingController workoutDescriptionController = + TextEditingController(); @override Widget build(BuildContext context) { @@ -56,13 +57,17 @@ class WorkoutForm extends StatelessWidget { children: [ TextFormField( key: const Key('field-name'), - decoration: InputDecoration(labelText: AppLocalizations.of(context).name), + decoration: + InputDecoration(labelText: AppLocalizations.of(context).name), controller: workoutNameController, validator: (value) { const minLength = 1; const maxLength = 100; - if (value!.isEmpty || value.length < minLength || value.length > maxLength) { - return AppLocalizations.of(context).enterCharacters(minLength, maxLength); + if (value!.isEmpty || + value.length < minLength || + value.length > maxLength) { + return AppLocalizations.of(context) + .enterCharacters(minLength, maxLength); } return null; }, @@ -82,7 +87,8 @@ class WorkoutForm extends StatelessWidget { const minLength = 0; const maxLength = 1000; if (value!.length > maxLength) { - return AppLocalizations.of(context).enterCharacters(minLength, maxLength); + return AppLocalizations.of(context) + .enterCharacters(minLength, maxLength); } return null; }, @@ -103,12 +109,14 @@ class WorkoutForm extends StatelessWidget { // Save to DB if (_plan.id != null) { - await Provider.of(context, listen: false).editWorkout(_plan); + await Provider.of(context, listen: false) + .editWorkout(_plan); if (context.mounted) { Navigator.of(context).pop(); } } else { - final WorkoutPlan newPlan = await Provider.of( + final WorkoutPlan newPlan = + await Provider.of( context, listen: false, ).addWorkout(_plan); @@ -200,8 +208,11 @@ class _DayFormWidgetState extends State { validator: (value) { const minLength = 1; const maxLength = 100; - if (value!.isEmpty || value.length < minLength || value.length > maxLength) { - return AppLocalizations.of(context).enterCharacters(minLength, maxLength); + if (value!.isEmpty || + value.length < minLength || + value.length > maxLength) { + return AppLocalizations.of(context) + .enterCharacters(minLength, maxLength); } if (widget._day.daysOfWeek.isEmpty) { @@ -223,12 +234,14 @@ class _DayFormWidgetState extends State { try { if (widget._day.id == null) { - Provider.of(context, listen: false).addDay( + Provider.of(context, listen: false) + .addDay( widget._day, widget.workout, ); } else { - Provider.of(context, listen: false).editDay( + Provider.of(context, listen: false) + .editDay( widget._day, ); } @@ -334,7 +347,8 @@ class _SetFormWidgetState extends State { child: Column( //crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(AppLocalizations.of(context).nrOfSets(_currentSetSliderValue.round())), + Text(AppLocalizations.of(context) + .nrOfSets(_currentSetSliderValue.round())), Slider( value: _currentSetSliderValue, min: 1, @@ -387,7 +401,8 @@ class _SetFormWidgetState extends State { focusNode: focusNode, // autofocus: true, decoration: InputDecoration( - labelText: AppLocalizations.of(context).searchExercise, + labelText: + AppLocalizations.of(context).searchExercise, prefixIcon: const Icon(Icons.search), suffixIcon: IconButton( icon: const Icon(Icons.help), @@ -398,15 +413,18 @@ class _SetFormWidgetState extends State { content: Column( mainAxisSize: MainAxisSize.min, children: [ - Text(AppLocalizations.of(context).selectExercises), + Text(AppLocalizations.of(context) + .selectExercises), const SizedBox(height: 10), - Text(AppLocalizations.of(context).sameRepetitions), + Text(AppLocalizations.of(context) + .sameRepetitions), ], ), actions: [ TextButton( child: Text( - MaterialLocalizations.of(context).closeButtonLabel, + MaterialLocalizations.of(context) + .closeButtonLabel, ), onPressed: () { Navigator.of(context).pop(); @@ -423,15 +441,18 @@ class _SetFormWidgetState extends State { validator: (value) { // At least one exercise must be selected if (widget._set.exerciseBasesIds.isEmpty) { - return AppLocalizations.of(context).selectExercise; + return AppLocalizations.of(context) + .selectExercise; } // At least one setting has to be filled in if (widget._set.settings - .where((s) => s.weight == null && s.reps == null) + .where((s) => + s.weight == null && s.reps == null) .length == widget._set.settings.length) { - return AppLocalizations.of(context).enterRepetitionsOrWeight; + return AppLocalizations.of(context) + .enterRepetitionsOrWeight; } return null; }, @@ -441,9 +462,12 @@ class _SetFormWidgetState extends State { if (pattern == '') { return null; } - return context.read().searchExercise( + return context + .read() + .searchExercise( pattern, - languageCode: Localizations.localeOf(context).languageCode, + languageCode: Localizations.localeOf(context) + .languageCode, searchEnglish: _searchEnglish, ); }, @@ -461,7 +485,8 @@ class _SetFormWidgetState extends State { ), title: Text( exerciseSuggestion - .getExercise(Localizations.localeOf(context).languageCode) + .getExercise(Localizations.localeOf(context) + .languageCode) .name, ), subtitle: Text( @@ -473,20 +498,24 @@ class _SetFormWidgetState extends State { mainAxisSize: MainAxisSize.min, children: [ ListTile( - title: Text(AppLocalizations.of(context).noMatchingExerciseFound), + title: Text(AppLocalizations.of(context) + .noMatchingExerciseFound), ), ListTile( title: OutlinedButton( onPressed: () { - Navigator.of(context).pushNamed(AddExerciseScreen.routeName); + Navigator.of(context) + .pushNamed(AddExerciseScreen.routeName); }, - child: Text(AppLocalizations.of(context).contributeExercise), + child: Text(AppLocalizations.of(context) + .contributeExercise), ), ), ], ); }, - transitionBuilder: (context, animation, child) => FadeTransition( + transitionBuilder: (context, animation, child) => + FadeTransition( opacity: CurvedAnimation( parent: animation, curve: Curves.fastOutSlowIn, @@ -500,9 +529,11 @@ class _SetFormWidgetState extends State { _exercisesController.text = ''; }, ), - if (Localizations.localeOf(context).languageCode != LANGUAGE_SHORT_ENGLISH) + if (Localizations.localeOf(context).languageCode != + LANGUAGE_SHORT_ENGLISH) SwitchListTile( - title: Text(AppLocalizations.of(context).searchNamesInEnglish), + title: Text(AppLocalizations.of(context) + .searchNamesInEnglish), value: _searchEnglish, onChanged: (_) { setState(() { @@ -525,7 +556,8 @@ class _SetFormWidgetState extends State { const minLength = 0; const maxLength = 200; if (value!.length > maxLength) { - return AppLocalizations.of(context).enterCharacters(minLength, maxLength); + return AppLocalizations.of(context) + .enterCharacters(minLength, maxLength); } return null; }, @@ -537,9 +569,11 @@ class _SetFormWidgetState extends State { ...widget._set.exerciseBasesObj.asMap().entries.map((entry) { final index = entry.key; final exercise = entry.value; - final showSupersetInfo = (index + 1) < widget._set.exerciseBasesObj.length; - final settings = - widget._set.settings.where((e) => e.exerciseObj.id == exercise.id).toList(); + final showSupersetInfo = + (index + 1) < widget._set.exerciseBasesObj.length; + final settings = widget._set.settings + .where((e) => e.exerciseObj.id == exercise.id) + .toList(); return Column( children: [ @@ -555,7 +589,8 @@ class _SetFormWidgetState extends State { padding: EdgeInsets.all(3.0), child: Text('+'), ), - if (showSupersetInfo) Text(AppLocalizations.of(context).supersetWith), + if (showSupersetInfo) + Text(AppLocalizations.of(context).supersetWith), if (showSupersetInfo) const Padding( padding: EdgeInsets.all(3.0), @@ -584,14 +619,16 @@ class _SetFormWidgetState extends State { widget._set.id = setDb.id; // Remove unused settings - widget._set.settings.removeWhere((s) => s.weight == null && s.reps == null); + widget._set.settings + .removeWhere((s) => s.weight == null && s.reps == null); // Save remaining settings for (final setting in widget._set.settings) { setting.setId = setDb.id!; setting.comment = ''; - final Setting settingDb = await workoutProvider.addSetting(setting); + final Setting settingDb = + await workoutProvider.addSetting(setting); setting.id = settingDb.id; } @@ -669,11 +706,12 @@ class ExerciseSetting extends StatelessWidget { const SizedBox(width: 4), Flexible( flex: 3, - child: WeightUnitInputWidget(setting, key: Key(i.toString())), + child: + WeightUnitInputWidget(setting, key: Key(i.toString())), ), ], ), - Flexible(flex: 2, child: RiRInputWidget(setting)), + Flexible(flex: 2, child: RiRInputWidget(setting: setting)), const SizedBox(height: 15), ], ), @@ -710,7 +748,9 @@ class ExerciseSetting extends StatelessWidget { children: [ ListTile( title: Text( - _exerciseBase.getExercise(Localizations.localeOf(context).languageCode).name, + _exerciseBase + .getExercise(Localizations.localeOf(context).languageCode) + .name, style: Theme.of(context).textTheme.titleLarge, ), subtitle: Text(_exerciseBase.category!.name), @@ -819,33 +859,29 @@ class WeightInputWidget extends StatelessWidget { /// Input widget for Rests In Reserve /// /// Can be used with a Setting or a Log object -class RiRInputWidget extends StatefulWidget { - final dynamic _setting; - late String dropdownValue; - late double _currentSetSliderValue; - static const SLIDER_START = -0.5; - - RiRInputWidget(this._setting) { - dropdownValue = _setting.rir ?? Setting.DEFAULT_RIR; +class RiRInputWidget extends StatefulWidget { + final dynamic setting; - // Read string RiR into a double - if (_setting.rir != null) { - if (_setting.rir == '') { - _currentSetSliderValue = SLIDER_START; - } else { - _currentSetSliderValue = double.parse(_setting.rir); - } - } else { - _currentSetSliderValue = SLIDER_START; - } - } + const RiRInputWidget({required this.setting, Key? key}) : super(key: key); @override - _RiRInputWidgetState createState() => _RiRInputWidgetState(); + State createState() => _RiRInputWidgetState(); } class _RiRInputWidgetState extends State { + static const double sliderStart = -0.5; + late double currentSetSliderValue; + + @override + void initState() { + super.initState(); + currentSetSliderValue = + widget.setting.rir == null || widget.setting.rir.isEmpty + ? sliderStart + : double.tryParse(widget.setting.rir) ?? sliderStart; + } + /// Returns the string used in the slider String getSliderLabel(double value) { if (value < 0) { @@ -854,19 +890,6 @@ class _RiRInputWidgetState extends State { return '$value ${AppLocalizations.of(context).rir}'; } - String mapDoubleToAllowedRir(double value) { - if (value < 0) { - return ''; - } else { - // The representation is different (3.0 -> 3) we are on an int, round - if (value.toInt() < value) { - return value.toString(); - } else { - return value.toInt().toString(); - } - } - } - @override Widget build(BuildContext context) { return Row( @@ -875,15 +898,15 @@ class _RiRInputWidgetState extends State { Text(AppLocalizations.of(context).rir), Expanded( child: Slider( - value: widget._currentSetSliderValue, - min: RiRInputWidget.SLIDER_START, - max: (Setting.POSSIBLE_RIR_VALUES.length - 2) / 2, - divisions: Setting.POSSIBLE_RIR_VALUES.length - 1, - label: getSliderLabel(widget._currentSetSliderValue), - onChanged: (double value) { - widget._setting.setRir(mapDoubleToAllowedRir(value)); + value: currentSetSliderValue, + min: sliderStart, + max: 5.0, + divisions: 11, + label: getSliderLabel(currentSetSliderValue), + onChanged: (value) { setState(() { - widget._currentSetSliderValue = value; + currentSetSliderValue = value; + widget.setting.rir = value < 0 ? '' : value.toString(); }); }, ), @@ -912,7 +935,8 @@ class _WeightUnitInputWidgetState extends State { return DropdownButtonFormField( value: selectedWeightUnit, - decoration: InputDecoration(labelText: AppLocalizations.of(context).weightUnit), + decoration: + InputDecoration(labelText: AppLocalizations.of(context).weightUnit), onChanged: (WeightUnit? newValue) { setState(() { selectedWeightUnit = newValue!; @@ -941,7 +965,8 @@ class RepetitionUnitInputWidget extends StatefulWidget { const RepetitionUnitInputWidget(this._setting); @override - _RepetitionUnitInputWidgetState createState() => _RepetitionUnitInputWidgetState(); + _RepetitionUnitInputWidgetState createState() => + _RepetitionUnitInputWidgetState(); } class _RepetitionUnitInputWidgetState extends State { diff --git a/lib/widgets/workouts/gym_mode.dart b/lib/widgets/workouts/gym_mode.dart index 27a878737..9b09b876c 100644 --- a/lib/widgets/workouts/gym_mode.dart +++ b/lib/widgets/workouts/gym_mode.dart @@ -1,3 +1,5 @@ +// ignore_for_file: use_build_context_synchronously + /* * This file is part of wger Workout Manager . * Copyright (C) 2020, 2021 wger Team @@ -27,7 +29,6 @@ import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/gym_mode.dart'; import 'package:wger/helpers/i18n.dart'; import 'package:wger/helpers/json.dart'; -import 'package:wger/helpers/misc.dart'; import 'package:wger/helpers/ui.dart'; import 'package:wger/models/exercises/exercise.dart'; import 'package:wger/models/workouts/day.dart'; @@ -83,8 +84,9 @@ class _GymModeState extends State { for (final set in widget._workoutDay.sets) { var firstPage = true; for (final setting in set.settingsComputed) { - final exerciseBase = Provider.of(context, listen: false) - .findExerciseById(setting.exerciseId); + final exerciseBase = + Provider.of(context, listen: false) + .findExerciseById(setting.exerciseId); if (firstPage) { _exercisePages[exerciseBase] = currentPage; @@ -103,8 +105,10 @@ class _GymModeState extends State { // Returns the list of exercise overview, sets and pause pages List getContent() { - final exerciseProvider = Provider.of(context, listen: false); - final workoutProvider = Provider.of(context, listen: false); + final exerciseProvider = + Provider.of(context, listen: false); + final workoutProvider = + Provider.of(context, listen: false); var currentElement = 1; final List out = []; @@ -112,7 +116,8 @@ class _GymModeState extends State { var firstPage = true; for (final setting in set.settingsComputed) { final ratioCompleted = currentElement / _totalElements; - final exerciseBase = exerciseProvider.findExerciseById(setting.exerciseId); + final exerciseBase = + exerciseProvider.findExerciseById(setting.exerciseId); currentElement++; if (firstPage) { @@ -188,11 +193,14 @@ class StartPage extends StatelessWidget { children: [ Text( s.exerciseObj - .getExercise(Localizations.localeOf(context).languageCode) + .getExercise(Localizations.localeOf(context) + .languageCode) .name, style: Theme.of(context).textTheme.titleLarge, ), - ...set.getSmartRepr(s.exerciseObj).map((e) => Text(e)), + ...set + .getSmartRepr(s.exerciseObj) + .map((e) => Text(e)), const SizedBox(height: 15), ], ); @@ -341,7 +349,8 @@ class _LogPageState extends State { icon: const Icon(Icons.remove, color: Colors.black), onPressed: () { try { - final double newValue = double.parse(_weightController.text) - (2 * minPlateWeight); + final double newValue = + double.parse(_weightController.text) - (2 * minPlateWeight); if (newValue > 0) { setState(() { widget._log.weight = newValue; @@ -386,7 +395,8 @@ class _LogPageState extends State { icon: const Icon(Icons.add, color: Colors.black), onPressed: () { try { - final double newValue = double.parse(_weightController.text) + (2 * minPlateWeight); + final double newValue = + double.parse(_weightController.text) + (2 * minPlateWeight); setState(() { widget._log.weight = newValue; _weightController.text = newValue.toString(); @@ -435,7 +445,7 @@ class _LogPageState extends State { Flexible(child: WeightUnitInputWidget(widget._log)), ], ), - if (_detailed) RiRInputWidget(widget._log), + if (_detailed) RiRInputWidget(setting: widget._log), SwitchListTile( title: Text(AppLocalizations.of(context).setUnitsAndRir), value: _detailed, @@ -463,15 +473,18 @@ class _LogPageState extends State { context, listen: false, ).addLog(widget._log); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - duration: const Duration(seconds: 2), // default is 4 - content: Text( - AppLocalizations.of(context).successfullySaved, - textAlign: TextAlign.center, + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + duration: + const Duration(seconds: 2), // default is 4 + content: Text( + AppLocalizations.of(context).successfullySaved, + textAlign: TextAlign.center, + ), ), - ), - ); + ); + } widget._controller.nextPage( duration: DEFAULT_ANIMATION_DURATION, curve: DEFAULT_ANIMATION_CURVE, @@ -518,7 +531,8 @@ class _LogPageState extends State { return ListTile( title: Text(log.singleLogRepTextNoNl), subtitle: Text( - DateFormat.yMd(Localizations.localeOf(context).languageCode).format(log.date), + DateFormat.yMd(Localizations.localeOf(context).languageCode) + .format(log.date), ), trailing: const Icon(Icons.copy), onTap: () { @@ -572,11 +586,14 @@ class _LogPageState extends State { const Text('×'), Container( decoration: BoxDecoration( - color: Theme.of(context).colorScheme.primaryContainer, + color: Theme.of(context) + .colorScheme + .primaryContainer, shape: BoxShape.circle, ), child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 3), + padding: + const EdgeInsets.symmetric(horizontal: 3), child: SizedBox( height: 35, width: 35, @@ -612,7 +629,9 @@ class _LogPageState extends State { return Column( children: [ NavigationHeader( - widget._exerciseBase.getExercise(Localizations.localeOf(context).languageCode).name, + widget._exerciseBase + .getExercise(Localizations.localeOf(context).languageCode) + .name, widget._controller, exercisePages: widget._exercisePages, ), @@ -623,15 +642,20 @@ class _LogPageState extends State { textAlign: TextAlign.center, ), ), - if (widget._set.comment != '') Text(widget._set.comment, textAlign: TextAlign.center), + if (widget._set.comment != '') + Text(widget._set.comment, textAlign: TextAlign.center), const SizedBox(height: 10), Expanded( - child: (widget._workoutPlan.filterLogsByExerciseBase(widget._exerciseBase).isNotEmpty) + child: (widget._workoutPlan + .filterLogsByExerciseBase(widget._exerciseBase) + .isNotEmpty) ? getPastLogs() : Container(), ), // Only show calculator for barbell - if (widget._log.exerciseBaseObj.equipment.map((e) => e.id).contains(ID_EQUIPMENT_BARBELL)) + if (widget._log.exerciseBaseObj.equipment + .map((e) => e.id) + .contains(ID_EQUIPMENT_BARBELL)) getPlates(), Padding( padding: const EdgeInsets.symmetric(horizontal: 15), @@ -661,7 +685,9 @@ class ExerciseOverview extends StatelessWidget { return Column( children: [ NavigationHeader( - _exerciseBase.getExercise(Localizations.localeOf(context).languageCode).name, + _exerciseBase + .getExercise(Localizations.localeOf(context).languageCode) + .name, _controller, exercisePages: _exercisePages, ), @@ -672,7 +698,8 @@ class ExerciseOverview extends StatelessWidget { children: [ Text( getTranslation(_exerciseBase.category!.name, context), - semanticsLabel: getTranslation(_exerciseBase.category!.name, context), + semanticsLabel: + getTranslation(_exerciseBase.category!.name, context), style: Theme.of(context).textTheme.titleLarge, textAlign: TextAlign.center, ), @@ -688,7 +715,8 @@ class ExerciseOverview extends StatelessWidget { child: ListView( scrollDirection: Axis.horizontal, children: [ - ..._exerciseBase.images.map((e) => ExerciseImageWidget(image: e)), + ..._exerciseBase.images + .map((e) => ExerciseImageWidget(image: e)), ], ), ), @@ -830,7 +858,8 @@ class _SessionPageState extends State { ); if (pickedTime != null) { - timeStartController.text = timeToString(pickedTime)!; + timeStartController.text = + timeToString(pickedTime)!; _session.timeStart = pickedTime; } }, @@ -838,8 +867,10 @@ class _SessionPageState extends State { _session.timeStart = stringToTime(newValue); }, validator: (_) { - final TimeOfDay startTime = stringToTime(timeStartController.text); - final TimeOfDay endTime = stringToTime(timeEndController.text); + final TimeOfDay startTime = + stringToTime(timeStartController.text); + final TimeOfDay endTime = + stringToTime(timeEndController.text); if (startTime.isAfter(endTime)) { return AppLocalizations.of(context).timeStartAhead; } @@ -986,7 +1017,10 @@ class _TimerWidgetState extends State { child: Center( child: Text( DateFormat('m:ss').format(today.add(Duration(seconds: _seconds))), - style: Theme.of(context).textTheme.displayLarge!.copyWith(color: wgerPrimaryColor), + style: Theme.of(context) + .textTheme + .displayLarge! + .copyWith(color: wgerPrimaryColor), ), ), ), @@ -1072,7 +1106,9 @@ class NavigationHeader extends StatelessWidget { children: [ ...exercisePages.keys.map((e) { return ListTile( - title: Text(e.getExercise(Localizations.localeOf(context).languageCode).name), + title: Text(e + .getExercise(Localizations.localeOf(context).languageCode) + .name), trailing: const Icon(Icons.chevron_right), onTap: () { _controller.animateToPage( diff --git a/lib/widgets/workouts/log.dart b/lib/widgets/workouts/log.dart index e59def77f..fe02d75d8 100644 --- a/lib/widgets/workouts/log.dart +++ b/lib/widgets/workouts/log.dart @@ -30,13 +30,13 @@ import 'package:wger/widgets/workouts/charts.dart'; class ExerciseLogChart extends StatelessWidget { final Exercise _base; - final DateTime _currentDate; - const ExerciseLogChart(this._base, this._currentDate); + const ExerciseLogChart(this._base); @override Widget build(BuildContext context) { - final workoutPlansData = Provider.of(context, listen: false); + final workoutPlansData = + Provider.of(context, listen: false); final workout = workoutPlansData.currentPlan; var colors = generateChartColors(1).iterator; @@ -48,7 +48,8 @@ class ExerciseLogChart extends StatelessWidget { future: getChartEntries(context), builder: (context, AsyncSnapshot> snapshot) { if (snapshot.connectionState == ConnectionState.done) { - colors = generateChartColors(snapshot.data!['chart_data'].length).iterator; + colors = + generateChartColors(snapshot.data!['chart_data'].length).iterator; } return SizedBox( @@ -58,7 +59,7 @@ class ExerciseLogChart extends StatelessWidget { : Column( mainAxisSize: MainAxisSize.max, children: [ - LogChartWidgetFl(snapshot.data!, _currentDate), + LogChartWidgetFl(snapshot.data!), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ @@ -108,12 +109,14 @@ class _DayLogWidgetState extends State { child: Column( children: [ Text( - DateFormat.yMd(Localizations.localeOf(context).languageCode).format(widget._date), + DateFormat.yMd(Localizations.localeOf(context).languageCode) + .format(widget._date), style: Theme.of(context).textTheme.headlineSmall, ), if (widget._session != null) const Text('Session data here'), ...widget._exerciseData.keys.map((base) { - final exercise = base.getExercise(Localizations.localeOf(context).languageCode); + final exercise = + base.getExercise(Localizations.localeOf(context).languageCode); return Column( children: [ if (widget._exerciseData[base]!.isNotEmpty) @@ -145,7 +148,7 @@ class _DayLogWidgetState extends State { ), Padding( padding: const EdgeInsets.symmetric(horizontal: 15), - child: ExerciseLogChart(base, widget._date), + child: ExerciseLogChart(base), ), ], ); diff --git a/lib/widgets/workouts/workout_plan_detail.dart b/lib/widgets/workouts/workout_plan_detail.dart index 5fcfd7c78..00e23489d 100644 --- a/lib/widgets/workouts/workout_plan_detail.dart +++ b/lib/widgets/workouts/workout_plan_detail.dart @@ -61,7 +61,8 @@ class _WorkoutPlanDetailState extends State { padding: const EdgeInsets.all(15), child: Text(widget._workoutPlan.description), ), - ...widget._workoutPlan.days.map((workoutDay) => WorkoutDayWidget(workoutDay)), + ...widget._workoutPlan.days + .map((workoutDay) => WorkoutDayWidget(workoutDay)), Column( children: [ ElevatedButton( diff --git a/lib/widgets/workouts/workout_plans_list.dart b/lib/widgets/workouts/workout_plans_list.dart index 14112ab13..8a54c2525 100644 --- a/lib/widgets/workouts/workout_plans_list.dart +++ b/lib/widgets/workouts/workout_plans_list.dart @@ -69,20 +69,24 @@ class WorkoutPlansList extends StatelessWidget { builder: (BuildContext contextDialog) { return AlertDialog( content: Text( - AppLocalizations.of(context).confirmDelete(currentWorkout.name), + AppLocalizations.of(context) + .confirmDelete(currentWorkout.name), ), actions: [ TextButton( child: Text( - MaterialLocalizations.of(context).cancelButtonLabel, + MaterialLocalizations.of(context) + .cancelButtonLabel, ), - onPressed: () => Navigator.of(contextDialog).pop(), + onPressed: () => + Navigator.of(contextDialog).pop(), ), TextButton( child: Text( AppLocalizations.of(context).delete, style: TextStyle( - color: Theme.of(context).colorScheme.error, + color: + Theme.of(context).colorScheme.error, ), ), onPressed: () { @@ -96,10 +100,12 @@ class WorkoutPlansList extends StatelessWidget { Navigator.of(contextDialog).pop(); // and inform the user - ScaffoldMessenger.of(context).showSnackBar( + ScaffoldMessenger.of(context) + .showSnackBar( SnackBar( content: Text( - AppLocalizations.of(context).successfullyDeleted, + AppLocalizations.of(context) + .successfullyDeleted, textAlign: TextAlign.center, ), ), diff --git a/pubspec.lock b/pubspec.lock index e65a68f92..4ad650457 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -22,22 +22,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.11.0" - analyzer_plugin: - dependency: transitive - description: - name: analyzer_plugin - sha256: "9661b30b13a685efaee9f02e5d01ed9f2b423bd889d28a304d02d704aee69161" - url: "https://pub.dev" - source: hosted - version: "0.11.3" archive: dependency: transitive description: name: archive - sha256: "08064924cbf0ab88280a0c3f60db9dd24fec693927e725ecb176f16c629d1cb8" + sha256: "6199c74e3db4fbfbd04f66d739e72fe11c8a8957d5f219f1f4482dbde6420b5a" url: "https://pub.dev" source: hosted - version: "4.0.1" + version: "4.0.2" args: dependency: transitive description: @@ -66,34 +58,34 @@ packages: dependency: transitive description: name: build - sha256: "80184af8b6cb3e5c1c4ec6d8544d27711700bc3e6d2efad04238c7b5290889f0" + sha256: cef23f1eda9b57566c81e2133d196f8e3df48f244b317368d65c5943d91148f0 url: "https://pub.dev" source: hosted - version: "2.4.1" + version: "2.4.2" build_config: dependency: transitive description: name: build_config - sha256: bf80fcfb46a29945b423bd9aad884590fb1dc69b330a4d4700cac476af1708d1 + sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33" url: "https://pub.dev" source: hosted - version: "1.1.1" + version: "1.1.2" build_daemon: dependency: transitive description: name: build_daemon - sha256: "79b2aef6ac2ed00046867ed354c88778c9c0f029df8a20fe10b5436826721ef9" + sha256: "294a2edaf4814a378725bfe6358210196f5ea37af89ecd81bfa32960113d4948" url: "https://pub.dev" source: hosted - version: "4.0.2" + version: "4.0.3" build_resolvers: dependency: transitive description: name: build_resolvers - sha256: "339086358431fa15d7eca8b6a36e5d783728cf025e559b834f4609a1fcfb7b0a" + sha256: "99d3980049739a985cf9b21f30881f46db3ebc62c5b8d5e60e27440876b1ba1e" url: "https://pub.dev" source: hosted - version: "2.4.2" + version: "2.4.3" build_runner: dependency: "direct dev" description: @@ -122,10 +114,10 @@ packages: dependency: transitive description: name: built_value - sha256: c7913a9737ee4007efedaffc968c049fd0f3d0e49109e778edc10de9426005cb + sha256: "28a712df2576b63c6c005c465989a348604960c0958d28be5303ba9baa841ac2" url: "https://pub.dev" source: hosted - version: "8.9.2" + version: "8.9.3" camera: dependency: transitive description: @@ -138,18 +130,18 @@ packages: dependency: transitive description: name: camera_android_camerax - sha256: e3627fdc2132d89212b8a8676679f5b07008c7e3d8ae00cea775c3397f9e742b + sha256: abcfa1ac32bd03116b4cfda7e8223ab391f01966e65823c064afe388550d1b3d url: "https://pub.dev" source: hosted - version: "0.6.10" + version: "0.6.10+3" camera_avfoundation: dependency: transitive description: name: camera_avfoundation - sha256: "2e4c568f70e406ccb87376bc06b53d2f5bebaab71e2fbcc1a950e31449381bcf" + sha256: c3038e6e72e284b14ad246a419f26908c08f8886d114cb8a2e351988439bfa68 url: "https://pub.dev" source: hosted - version: "0.9.17+5" + version: "0.9.17+6" camera_platform_interface: dependency: transitive description: @@ -178,10 +170,10 @@ packages: dependency: transitive description: name: change - sha256: "65db7f966dc7e786687f49900a94c5f08b0eb9ca8c4a3e7eed3a55e980b455e2" + sha256: "3bda1ce98526b21927cdea05688563c7065fd7e66d1abbe176c354fef3b2057b" url: "https://pub.dev" source: hosted - version: "0.7.4" + version: "0.7.5" characters: dependency: transitive description: @@ -290,26 +282,26 @@ packages: dependency: transitive description: name: dart_style - sha256: "7856d364b589d1f08986e140938578ed36ed948581fbc3bc9aef1805039ac5ab" + sha256: "27eb0ae77836989a3bc541ce55595e8ceee0992807f14511552a898ddd0d88ac" url: "https://pub.dev" source: hosted - version: "2.3.7" + version: "3.0.1" drift: dependency: "direct main" description: name: drift - sha256: c2d073d35ad441730812f4ea05b5dd031fb81c5f9786a4f5fb77ecd6307b6f74 + sha256: af3941e4d544727b2eb80590eb64e9cb8d77cd68c7690265502ea6a2427aa621 url: "https://pub.dev" source: hosted - version: "2.22.1" + version: "2.23.1" drift_dev: dependency: "direct dev" description: name: drift_dev - sha256: f4ab5d6976b1e31551ceb82ff597a505bda7818ff4f7be08a1da9d55eb6e730c + sha256: fa98fdbb7303a1b5b2dc110cb516eda2253a5d291680f8cbc72b1af24099f7f9 url: "https://pub.dev" source: hosted - version: "2.22.1" + version: "2.23.1" equatable: dependency: "direct main" description: @@ -386,26 +378,26 @@ packages: dependency: "direct main" description: name: fl_chart - sha256: "74959b99b92b9eebeed1a4049426fd67c4abc3c5a0f4d12e2877097d6a11ae08" + sha256: "10ddaf334fe84d59333a12d153043e366f243e0bdfff2df0313e1e249f5bf926" url: "https://pub.dev" source: hosted - version: "0.69.2" + version: "0.70.1" flex_color_scheme: dependency: "direct main" description: name: flex_color_scheme - sha256: "90f4fe67b9561ae8a4af117df65a8ce9988624025667c54e6d304e65cff77d52" + sha256: "09bea5d776f694c5a67f2229f2aa500cc7cce369322dc6500ab01cf9ad1b4e1a" url: "https://pub.dev" source: hosted - version: "8.0.2" + version: "8.1.0" flex_seed_scheme: dependency: "direct main" description: name: flex_seed_scheme - sha256: "7639d2c86268eff84a909026eb169f008064af0fb3696a651b24b0fa24a40334" + sha256: d3ba3c5c92d2d79d45e94b4c6c71d01fac3c15017da1545880c53864da5dfeb0 url: "https://pub.dev" source: hosted - version: "3.4.1" + version: "3.5.0" flutter: dependency: "direct main" description: flutter @@ -505,10 +497,10 @@ packages: dependency: transitive description: name: flutter_plugin_android_lifecycle - sha256: "9b78450b89f059e96c9ebb355fa6b3df1d6b330436e0b885fb49594c41721398" + sha256: "615a505aef59b151b46bbeef55b36ce2b6ed299d160c51d84281946f0aa0ce0e" url: "https://pub.dev" source: hosted - version: "2.0.23" + version: "2.0.24" flutter_staggered_grid_view: dependency: "direct main" description: @@ -571,10 +563,10 @@ packages: dependency: "direct dev" description: name: freezed - sha256: "44c19278dd9d89292cf46e97dc0c1e52ce03275f40a97c5a348e802a924bf40e" + sha256: "62b248b2dfb06ded10c84b713215b25aea020a5b08c32e801a974361557ebc3f" url: "https://pub.dev" source: hosted - version: "2.5.7" + version: "3.0.0-0.0.dev" freezed_annotation: dependency: "direct main" description: @@ -648,26 +640,26 @@ packages: dependency: transitive description: name: http_multi_server - sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 url: "https://pub.dev" source: hosted - version: "3.2.1" + version: "3.2.2" http_parser: dependency: transitive description: name: http_parser - sha256: "76d306a1c3afb33fe82e2bbacad62a61f409b5634c915fceb0d799de1a913360" + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" url: "https://pub.dev" source: hosted - version: "4.1.1" + version: "4.1.2" image: dependency: transitive description: name: image - sha256: "599d08e369969bdf83138f5b4e0a7e823d3f992f23b8a64dd626877c37013533" + sha256: "8346ad4b5173924b5ddddab782fc7d8a6300178c8b1dc427775405a01701c4a6" url: "https://pub.dev" source: hosted - version: "4.4.0" + version: "4.5.2" image_picker: dependency: "direct main" description: @@ -680,10 +672,10 @@ packages: dependency: transitive description: name: image_picker_android - sha256: fa8141602fde3f7e2f81dbf043613eb44dfa325fa0bcf93c0f142c9f7a2c193e + sha256: aa6f1280b670861ac45220cc95adc59bb6ae130259d36f980ccb62220dc5e59f url: "https://pub.dev" source: hosted - version: "0.8.12+18" + version: "0.8.12+19" image_picker_for_web: dependency: transitive description: @@ -696,10 +688,10 @@ packages: dependency: transitive description: name: image_picker_ios - sha256: "4f0568120c6fcc0aaa04511cb9f9f4d29fc3d0139884b1d06be88dcec7641d6b" + sha256: "05da758e67bc7839e886b3959848aa6b44ff123ab4b28f67891008afe8ef9100" url: "https://pub.dev" source: hosted - version: "0.8.12+1" + version: "0.8.12+2" image_picker_linux: dependency: transitive description: @@ -773,10 +765,10 @@ packages: dependency: "direct dev" description: name: json_serializable - sha256: c2fcb3920cf2b6ae6845954186420fca40bc0a8abcc84903b7801f17d7050d7c + sha256: "8f52361c07497a7f2c16c13aac159f9be6fb12b1d67719eac98a21d9a205d571" url: "https://pub.dev" source: hosted - version: "6.9.0" + version: "6.9.2" leak_tracker: dependency: transitive description: @@ -805,10 +797,10 @@ packages: dependency: transitive description: name: lints - sha256: "4a16b3f03741e1252fda5de3ce712666d010ba2122f8e912c94f9f7b90e1a4c3" + sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 url: "https://pub.dev" source: hosted - version: "5.1.0" + version: "5.1.1" list_counter: dependency: transitive description: @@ -885,10 +877,10 @@ packages: dependency: "direct dev" description: name: mockito - sha256: "6841eed20a7befac0ce07df8116c8b8233ed1f4486a7647c7fc5a02ae6163917" + sha256: f99d8d072e249f719a5531735d146d8cf04c580d93920b04de75bef6dfb2daf6 url: "https://pub.dev" source: hosted - version: "5.4.4" + version: "5.4.5" multi_select_flutter: dependency: "direct main" description: @@ -1101,10 +1093,10 @@ packages: dependency: transitive description: name: pubspec_parse - sha256: c799b721d79eb6ee6fa56f00c04b472dcd44a30d258fac2174a6ec57302678f8 + sha256: "81876843eb50dc2e1e5b151792c9a985c5ed2536914115ed04e9c8528f6647b0" url: "https://pub.dev" source: hosted - version: "1.3.0" + version: "1.4.0" recase: dependency: transitive description: @@ -1149,18 +1141,18 @@ packages: dependency: transitive description: name: shared_preferences_android - sha256: "7f172d1b06de5da47b6264c2692ee2ead20bbbc246690427cdb4fc301cd0c549" + sha256: "02a7d8a9ef346c9af715811b01fbd8e27845ad2c41148eefd31321471b41863d" url: "https://pub.dev" source: hosted - version: "2.3.4" + version: "2.4.0" shared_preferences_foundation: dependency: transitive description: name: shared_preferences_foundation - sha256: "07e050c7cd39bad516f8d64c455f04508d09df104be326d8c02551590a0d513d" + sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" url: "https://pub.dev" source: hosted - version: "2.5.3" + version: "2.5.4" shared_preferences_linux: dependency: transitive description: @@ -1226,18 +1218,18 @@ packages: dependency: transitive description: name: source_gen - sha256: "14658ba5f669685cd3d63701d01b31ea748310f7ab854e471962670abcf57832" + sha256: "35c8150ece9e8c8d263337a265153c3329667640850b9304861faea59fc98f6b" url: "https://pub.dev" source: hosted - version: "1.5.0" + version: "2.0.0" source_helper: dependency: transitive description: name: source_helper - sha256: "6adebc0006c37dd63fe05bca0a929b99f06402fc95aa35bf36d67f5c06de01fd" + sha256: "86d247119aedce8e63f4751bd9626fc9613255935558447569ad42f9f5b48b3c" url: "https://pub.dev" source: hosted - version: "1.3.4" + version: "1.3.5" source_span: dependency: transitive description: @@ -1290,10 +1282,10 @@ packages: dependency: transitive description: name: stream_transform - sha256: "14a00e794c7c11aa145a170587321aedce29769c08d7f58b1d141da75e3b1c6f" + sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.1.1" string_scanner: dependency: transitive description: @@ -1514,10 +1506,10 @@ packages: dependency: transitive description: name: watcher - sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" + sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104" url: "https://pub.dev" source: hosted - version: "1.1.0" + version: "1.1.1" web: dependency: transitive description: @@ -1554,10 +1546,10 @@ packages: dependency: transitive description: name: win32 - sha256: "8b338d4486ab3fbc0ba0db9f9b4f5239b6697fcee427939a40e720cbb9ee0a69" + sha256: "154360849a56b7b67331c21f09a386562d88903f90a1099c5987afc1912e1f29" url: "https://pub.dev" source: hosted - version: "5.9.0" + version: "5.10.0" xdg_directories: dependency: transitive description: @@ -1578,10 +1570,10 @@ packages: dependency: transitive description: name: yaml - sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce url: "https://pub.dev" source: hosted - version: "3.1.2" + version: "3.1.3" sdks: - dart: ">=3.6.0-0 <4.0.0" - flutter: ">=3.24.0" + dart: ">=3.6.0 <4.0.0" + flutter: ">=3.27.0" diff --git a/pubspec.yaml b/pubspec.yaml index d89018c7a..a90e9b234 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -38,7 +38,7 @@ dependencies: cupertino_icons: ^1.0.8 drift: ^2.16.0 equatable: ^2.0.7 - fl_chart: ^0.69.2 + fl_chart: ^0.70.1 flex_color_scheme: ^8.0.2 flex_seed_scheme: ^3.4.1 flutter_barcode_scanner: ^2.0.0 @@ -81,7 +81,7 @@ dev_dependencies: cider: ^0.2.7 drift_dev: ^2.22.0 flutter_lints: ^5.0.0 - freezed: ^2.5.7 + freezed: ^3.0.0-0.0.dev golden_toolkit: ^0.15.0 json_serializable: ^6.9.0 mockito: ^5.4.4 diff --git a/test/auth/auth_provider_test.dart b/test/auth/auth_provider_test.dart index 8c7d9db47..2606afae0 100644 --- a/test/auth/auth_provider_test.dart +++ b/test/auth/auth_provider_test.dart @@ -19,15 +19,17 @@ void main() { setUp(() { mockClient = MockClient(); - authProvider = AuthProvider(mockClient, false); + authProvider = AuthProvider(mockClient); authProvider.serverUrl = 'http://localhost'; }); group('min application version check', () { test('app version higher than min version', () async { // arrange - when(mockClient.get(tVersionUri)).thenAnswer((_) => Future(() => Response('"1.2.0"', 200))); - final updateNeeded = await authProvider.applicationUpdateRequired('1.3.0', testMetadata); + when(mockClient.get(tVersionUri)) + .thenAnswer((_) => Future(() => Response('"1.2.0"', 200))); + final updateNeeded = + await authProvider.applicationUpdateRequired('1.3.0', testMetadata); // assert expect(updateNeeded, false); @@ -35,8 +37,10 @@ void main() { test('app version higher than min version - 1', () async { // arrange - when(mockClient.get(tVersionUri)).thenAnswer((_) => Future(() => Response('"1.3"', 200))); - final updateNeeded = await authProvider.applicationUpdateRequired('1.1', testMetadata); + when(mockClient.get(tVersionUri)) + .thenAnswer((_) => Future(() => Response('"1.3"', 200))); + final updateNeeded = + await authProvider.applicationUpdateRequired('1.1', testMetadata); // assert expect(updateNeeded, true); @@ -44,8 +48,10 @@ void main() { test('app version higher than min version - 2', () async { // arrange - when(mockClient.get(tVersionUri)).thenAnswer((_) => Future(() => Response('"1.3.0"', 200))); - final updateNeeded = await authProvider.applicationUpdateRequired('1.1', testMetadata); + when(mockClient.get(tVersionUri)) + .thenAnswer((_) => Future(() => Response('"1.3.0"', 200))); + final updateNeeded = + await authProvider.applicationUpdateRequired('1.1', testMetadata); // assert expect(updateNeeded, true); @@ -53,8 +59,10 @@ void main() { test('app version equal as min version', () async { // arrange - when(mockClient.get(tVersionUri)).thenAnswer((_) => Future(() => Response('"1.3.0"', 200))); - final updateNeeded = await authProvider.applicationUpdateRequired('1.3.0', testMetadata); + when(mockClient.get(tVersionUri)) + .thenAnswer((_) => Future(() => Response('"1.3.0"', 200))); + final updateNeeded = + await authProvider.applicationUpdateRequired('1.3.0', testMetadata); // assert expect(updateNeeded, false); diff --git a/test/auth/auth_screen_test.dart b/test/auth/auth_screen_test.dart index c9a89cf48..86e24ff10 100644 --- a/test/auth/auth_screen_test.dart +++ b/test/auth/auth_screen_test.dart @@ -73,7 +73,7 @@ void main() { setUp(() { mockClient = MockClient(); - authProvider = AuthProvider(mockClient, false); + authProvider = AuthProvider(mockClient); authProvider.serverUrl = 'https://wger.de'; SharedPreferences.setMockInitialValues({}); @@ -89,15 +89,18 @@ void main() { tLogin, headers: anyNamed('headers'), body: anyNamed('body'), - )).thenAnswer((_) => Future(() => Response(json.encode(responseLoginOk), 200))); + )).thenAnswer( + (_) => Future(() => Response(json.encode(responseLoginOk), 200))); - when(mockClient.get(any)).thenAnswer((_) => Future(() => Response('"1.2.3.4"', 200))); + when(mockClient.get(any)) + .thenAnswer((_) => Future(() => Response('"1.2.3.4"', 200))); when(mockClient.post( tRegistration, headers: anyNamed('headers'), body: anyNamed('body'), - )).thenAnswer((_) => Future(() => Response(json.encode(responseRegistrationOk), 201))); + )).thenAnswer((_) => + Future(() => Response(json.encode(responseRegistrationOk), 201))); }); group('Login mode', () { @@ -126,8 +129,10 @@ void main() { await tester.pumpWidget(getWidget()); // Act - await tester.enterText(find.byKey(const Key('inputUsername')), 'testuser'); - await tester.enterText(find.byKey(const Key('inputPassword')), '123456789'); + await tester.enterText( + find.byKey(const Key('inputUsername')), 'testuser'); + await tester.enterText( + find.byKey(const Key('inputPassword')), '123456789'); await tester.tap(find.byKey(const Key('actionButton'))); await tester.pumpAndSettle(); @@ -141,7 +146,8 @@ void main() { )); }); - testWidgets('Login - wront username & password', (WidgetTester tester) async { + testWidgets('Login - wront username & password', + (WidgetTester tester) async { // Arrange await tester.binding.setSurfaceSize(const Size(1080, 1920)); tester.view.devicePixelRatio = 1.0; @@ -157,8 +163,10 @@ void main() { await tester.pumpWidget(getWidget()); // Act - await tester.enterText(find.byKey(const Key('inputUsername')), 'testuser'); - await tester.enterText(find.byKey(const Key('inputPassword')), '123456789'); + await tester.enterText( + find.byKey(const Key('inputUsername')), 'testuser'); + await tester.enterText( + find.byKey(const Key('inputPassword')), '123456789'); await tester.tap(find.byKey(const Key('actionButton'))); await tester.pumpAndSettle(); @@ -211,9 +219,12 @@ void main() { // Act await tester.tap(find.byKey(const Key('toggleActionButton'))); - await tester.enterText(find.byKey(const Key('inputUsername')), 'testuser'); - await tester.enterText(find.byKey(const Key('inputPassword')), '123456789'); - await tester.enterText(find.byKey(const Key('inputPassword2')), '123456789'); + await tester.enterText( + find.byKey(const Key('inputUsername')), 'testuser'); + await tester.enterText( + find.byKey(const Key('inputPassword')), '123456789'); + await tester.enterText( + find.byKey(const Key('inputPassword2')), '123456789'); await tester.tap(find.byKey(const Key('actionButton'))); await tester.pumpAndSettle(); @@ -226,7 +237,8 @@ void main() { )); }); - testWidgets('Registration - password problems', (WidgetTester tester) async { + testWidgets('Registration - password problems', + (WidgetTester tester) async { // Arrange await tester.binding.setSurfaceSize(const Size(1080, 1920)); tester.view.devicePixelRatio = 1.0; @@ -247,16 +259,20 @@ void main() { // Act await tester.tap(find.byKey(const Key('toggleActionButton'))); - await tester.enterText(find.byKey(const Key('inputUsername')), 'testuser'); - await tester.enterText(find.byKey(const Key('inputPassword')), '123456789'); - await tester.enterText(find.byKey(const Key('inputPassword2')), '123456789'); + await tester.enterText( + find.byKey(const Key('inputUsername')), 'testuser'); + await tester.enterText( + find.byKey(const Key('inputPassword')), '123456789'); + await tester.enterText( + find.byKey(const Key('inputPassword2')), '123456789'); await tester.tap(find.byKey(const Key('actionButton'))); await tester.pumpAndSettle(); // Assert expect(find.textContaining('An Error Occurred'), findsOne); expect(find.textContaining('This password is too common'), findsOne); - expect(find.textContaining('This password is entirely numeric'), findsOne); + expect( + find.textContaining('This password is entirely numeric'), findsOne); expect(find.textContaining('This field must be unique'), findsOne); verify(mockClient.post( diff --git a/test/auth/auth_screen_test.mocks.dart b/test/auth/auth_screen_test.mocks.dart index f2c7f3b98..6f556ac87 100644 --- a/test/auth/auth_screen_test.mocks.dart +++ b/test/auth/auth_screen_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/auth/auth_screen_test.dart. // Do not manually edit this file. @@ -19,30 +19,21 @@ import 'package:mockito/src/dummies.dart' as _i5; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { - _FakeResponse_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { - _FakeStreamedResponse_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeStreamedResponse_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [Client]. @@ -54,45 +45,27 @@ class MockClient extends _i1.Mock implements _i2.Client { } @override - _i3.Future<_i2.Response> head( - Uri? url, { - Map? headers, - }) => + _i3.Future<_i2.Response> head(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #head, - [url], - {#headers: headers}, - ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #head, - [url], - {#headers: headers}, + Invocation.method(#head, [url], {#headers: headers}), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method(#head, [url], {#headers: headers}), ), - )), + ), ) as _i3.Future<_i2.Response>); @override - _i3.Future<_i2.Response> get( - Uri? url, { - Map? headers, - }) => + _i3.Future<_i2.Response> get(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #get, - [url], - {#headers: headers}, - ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #get, - [url], - {#headers: headers}, + Invocation.method(#get, [url], {#headers: headers}), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method(#get, [url], {#headers: headers}), ), - )), + ), ) as _i3.Future<_i2.Response>); @override @@ -106,24 +79,18 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #post, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #post, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i3.Future<_i2.Response>); @override @@ -137,24 +104,18 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #put, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #put, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i3.Future<_i2.Response>); @override @@ -168,24 +129,18 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #patch, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #patch, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i3.Future<_i2.Response>); @override @@ -199,45 +154,30 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #delete, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #delete, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i3.Future<_i2.Response>); @override - _i3.Future read( - Uri? url, { - Map? headers, - }) => + _i3.Future read(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #read, - [url], - {#headers: headers}, - ), - returnValue: _i3.Future.value(_i5.dummyValue( - this, - Invocation.method( - #read, - [url], - {#headers: headers}, + Invocation.method(#read, [url], {#headers: headers}), + returnValue: _i3.Future.value( + _i5.dummyValue( + this, + Invocation.method(#read, [url], {#headers: headers}), ), - )), + ), ) as _i3.Future); @override @@ -246,37 +186,25 @@ class MockClient extends _i1.Mock implements _i2.Client { Map? headers, }) => (super.noSuchMethod( - Invocation.method( - #readBytes, - [url], - {#headers: headers}, - ), + Invocation.method(#readBytes, [url], {#headers: headers}), returnValue: _i3.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i3.Future<_i6.Uint8List>); @override _i3.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( - Invocation.method( - #send, - [request], - ), - returnValue: - _i3.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( - this, - Invocation.method( - #send, - [request], + Invocation.method(#send, [request]), + returnValue: _i3.Future<_i2.StreamedResponse>.value( + _FakeStreamedResponse_1( + this, + Invocation.method(#send, [request]), ), - )), + ), ) as _i3.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( - Invocation.method( - #close, - [], - ), + Invocation.method(#close, []), returnValueForMissingStub: null, ); } diff --git a/test/core/settings_test.dart b/test/core/settings_test.dart index 72806b48c..468264573 100644 --- a/test/core/settings_test.dart +++ b/test/core/settings_test.dart @@ -36,8 +36,10 @@ void main() { Widget createSettingsScreen({locale = 'en'}) { return MultiProvider( providers: [ - ChangeNotifierProvider(create: (context) => mockNutritionProvider), - ChangeNotifierProvider(create: (context) => mockExerciseProvider), + ChangeNotifierProvider( + create: (context) => mockNutritionProvider), + ChangeNotifierProvider( + create: (context) => mockExerciseProvider), ], child: MaterialApp( locale: Locale(locale), @@ -49,7 +51,8 @@ void main() { } group('Cache', () { - testWidgets('Test resetting the exercise cache', (WidgetTester tester) async { + testWidgets('Test resetting the exercise cache', + (WidgetTester tester) async { await tester.pumpWidget(createSettingsScreen()); await tester.tap(find.byKey(const ValueKey('cacheIconExercises'))); await tester.pumpAndSettle(); @@ -57,7 +60,8 @@ void main() { verify(mockExerciseProvider.clearAllCachesAndPrefs()); }); - testWidgets('Test resetting the ingredient cache', (WidgetTester tester) async { + testWidgets('Test resetting the ingredient cache', + (WidgetTester tester) async { await tester.pumpWidget(createSettingsScreen()); await tester.tap(find.byKey(const ValueKey('cacheIconIngredients'))); await tester.pumpAndSettle(); diff --git a/test/core/settings_test.mocks.dart b/test/core/settings_test.mocks.dart index 303216098..1172fe6da 100644 --- a/test/core/settings_test.mocks.dart +++ b/test/core/settings_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/core/settings_test.dart. // Do not manually edit this file. @@ -31,6 +31,7 @@ import 'package:wger/providers/nutrition.dart' as _i17; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -38,127 +39,67 @@ import 'package:wger/providers/nutrition.dart' as _i17; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExerciseDatabase_1 extends _i1.SmartFake implements _i3.ExerciseDatabase { - _FakeExerciseDatabase_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeExerciseDatabase_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExercise_2 extends _i1.SmartFake implements _i4.Exercise { - _FakeExercise_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeExercise_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExerciseCategory_3 extends _i1.SmartFake implements _i5.ExerciseCategory { - _FakeExerciseCategory_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeExerciseCategory_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeEquipment_4 extends _i1.SmartFake implements _i6.Equipment { - _FakeEquipment_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeEquipment_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMuscle_5 extends _i1.SmartFake implements _i7.Muscle { - _FakeMuscle_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMuscle_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeLanguage_6 extends _i1.SmartFake implements _i8.Language { - _FakeLanguage_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeLanguage_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIngredientDatabase_7 extends _i1.SmartFake implements _i9.IngredientDatabase { - _FakeIngredientDatabase_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIngredientDatabase_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeNutritionalPlan_8 extends _i1.SmartFake implements _i10.NutritionalPlan { - _FakeNutritionalPlan_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeNutritionalPlan_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMeal_9 extends _i1.SmartFake implements _i11.Meal { - _FakeMeal_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMeal_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMealItem_10 extends _i1.SmartFake implements _i12.MealItem { - _FakeMealItem_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMealItem_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIngredient_11 extends _i1.SmartFake implements _i13.Ingredient { - _FakeIngredient_11( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIngredient_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [ExercisesProvider]. @@ -189,10 +130,7 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override set database(_i3.ExerciseDatabase? _database) => super.noSuchMethod( - Invocation.setter( - #database, - _database, - ), + Invocation.setter(#database, _database), returnValueForMissingStub: null, ); @@ -204,10 +142,7 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override set exercises(List<_i4.Exercise>? _exercises) => super.noSuchMethod( - Invocation.setter( - #exercises, - _exercises, - ), + Invocation.setter(#exercises, _exercises), returnValueForMissingStub: null, ); @@ -220,10 +155,7 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override set filteredExercises(List<_i4.Exercise>? newFilteredExercises) => super.noSuchMethod( - Invocation.setter( - #filteredExercises, - newFilteredExercises, - ), + Invocation.setter(#filteredExercises, newFilteredExercises), returnValueForMissingStub: null, ); @@ -260,69 +192,47 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override set languages(List<_i8.Language>? languages) => super.noSuchMethod( - Invocation.setter( - #languages, - languages, - ), + Invocation.setter(#languages, languages), returnValueForMissingStub: null, ); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override _i15.Future setFilters(_i14.Filters? newFilters) => (super.noSuchMethod( - Invocation.method( - #setFilters, - [newFilters], - ), + Invocation.method(#setFilters, [newFilters]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override void initFilters() => super.noSuchMethod( - Invocation.method( - #initFilters, - [], - ), + Invocation.method(#initFilters, []), returnValueForMissingStub: null, ); @override _i15.Future findByFilters() => (super.noSuchMethod( - Invocation.method( - #findByFilters, - [], - ), + Invocation.method(#findByFilters, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i4.Exercise findExerciseById(int? id) => (super.noSuchMethod( - Invocation.method( - #findExerciseById, - [id], - ), + Invocation.method(#findExerciseById, [id]), returnValue: _FakeExercise_2( this, - Invocation.method( - #findExerciseById, - [id], - ), + Invocation.method(#findExerciseById, [id]), ), ) as _i4.Exercise); @@ -342,100 +252,64 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override _i5.ExerciseCategory findCategoryById(int? id) => (super.noSuchMethod( - Invocation.method( - #findCategoryById, - [id], - ), + Invocation.method(#findCategoryById, [id]), returnValue: _FakeExerciseCategory_3( this, - Invocation.method( - #findCategoryById, - [id], - ), + Invocation.method(#findCategoryById, [id]), ), ) as _i5.ExerciseCategory); @override _i6.Equipment findEquipmentById(int? id) => (super.noSuchMethod( - Invocation.method( - #findEquipmentById, - [id], - ), + Invocation.method(#findEquipmentById, [id]), returnValue: _FakeEquipment_4( this, - Invocation.method( - #findEquipmentById, - [id], - ), + Invocation.method(#findEquipmentById, [id]), ), ) as _i6.Equipment); @override _i7.Muscle findMuscleById(int? id) => (super.noSuchMethod( - Invocation.method( - #findMuscleById, - [id], - ), + Invocation.method(#findMuscleById, [id]), returnValue: _FakeMuscle_5( this, - Invocation.method( - #findMuscleById, - [id], - ), + Invocation.method(#findMuscleById, [id]), ), ) as _i7.Muscle); @override _i8.Language findLanguageById(int? id) => (super.noSuchMethod( - Invocation.method( - #findLanguageById, - [id], - ), + Invocation.method(#findLanguageById, [id]), returnValue: _FakeLanguage_6( this, - Invocation.method( - #findLanguageById, - [id], - ), + Invocation.method(#findLanguageById, [id]), ), ) as _i8.Language); @override _i15.Future fetchAndSetCategoriesFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetCategoriesFromApi, - [], - ), + Invocation.method(#fetchAndSetCategoriesFromApi, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override _i15.Future fetchAndSetMusclesFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetMusclesFromApi, - [], - ), + Invocation.method(#fetchAndSetMusclesFromApi, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override _i15.Future fetchAndSetEquipmentsFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetEquipmentsFromApi, - [], - ), + Invocation.method(#fetchAndSetEquipmentsFromApi, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override _i15.Future fetchAndSetLanguagesFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetLanguagesFromApi, - [], - ), + Invocation.method(#fetchAndSetLanguagesFromApi, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -443,17 +317,13 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override _i15.Future<_i4.Exercise> fetchAndSetExercise(int? exerciseId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetExercise, - [exerciseId], - ), - returnValue: _i15.Future<_i4.Exercise>.value(_FakeExercise_2( - this, - Invocation.method( - #fetchAndSetExercise, - [exerciseId], + Invocation.method(#fetchAndSetExercise, [exerciseId]), + returnValue: _i15.Future<_i4.Exercise>.value( + _FakeExercise_2( + this, + Invocation.method(#fetchAndSetExercise, [exerciseId]), ), - )), + ), ) as _i15.Future<_i4.Exercise>); @override @@ -462,53 +332,41 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { int? exerciseId, ) => (super.noSuchMethod( - Invocation.method( - #handleUpdateExerciseFromApi, - [ - database, - exerciseId, - ], - ), - returnValue: _i15.Future<_i4.Exercise>.value(_FakeExercise_2( - this, - Invocation.method( - #handleUpdateExerciseFromApi, - [ + Invocation.method(#handleUpdateExerciseFromApi, [ + database, + exerciseId, + ]), + returnValue: _i15.Future<_i4.Exercise>.value( + _FakeExercise_2( + this, + Invocation.method(#handleUpdateExerciseFromApi, [ database, exerciseId, - ], + ]), ), - )), + ), ) as _i15.Future<_i4.Exercise>); @override _i15.Future initCacheTimesLocalPrefs({dynamic forceInit = false}) => (super.noSuchMethod( - Invocation.method( - #initCacheTimesLocalPrefs, - [], - {#forceInit: forceInit}, - ), + Invocation.method(#initCacheTimesLocalPrefs, [], { + #forceInit: forceInit, + }), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override _i15.Future clearAllCachesAndPrefs() => (super.noSuchMethod( - Invocation.method( - #clearAllCachesAndPrefs, - [], - ), + Invocation.method(#clearAllCachesAndPrefs, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override _i15.Future fetchAndSetInitialData() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetInitialData, - [], - ), + Invocation.method(#fetchAndSetInitialData, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -531,10 +389,7 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override _i15.Future updateExerciseCache(_i3.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #updateExerciseCache, - [database], - ), + Invocation.method(#updateExerciseCache, [database]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -542,10 +397,7 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override _i15.Future fetchAndSetMuscles(_i3.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetMuscles, - [database], - ), + Invocation.method(#fetchAndSetMuscles, [database]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -553,10 +405,7 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override _i15.Future fetchAndSetCategories(_i3.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetCategories, - [database], - ), + Invocation.method(#fetchAndSetCategories, [database]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -564,10 +413,7 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override _i15.Future fetchAndSetLanguages(_i3.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetLanguages, - [database], - ), + Invocation.method(#fetchAndSetLanguages, [database]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -575,10 +421,7 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override _i15.Future fetchAndSetEquipments(_i3.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetEquipments, - [database], - ), + Invocation.method(#fetchAndSetEquipments, [database]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -586,54 +429,41 @@ class MockExercisesProvider extends _i1.Mock implements _i14.ExercisesProvider { @override _i15.Future> searchExercise( String? name, { - String? languageCode = r'en', + String? languageCode = 'en', bool? searchEnglish = false, }) => (super.noSuchMethod( Invocation.method( #searchExercise, [name], - { - #languageCode: languageCode, - #searchEnglish: searchEnglish, - }, + {#languageCode: languageCode, #searchEnglish: searchEnglish}, + ), + returnValue: _i15.Future>.value( + <_i4.Exercise>[], ), - returnValue: _i15.Future>.value(<_i4.Exercise>[]), ) as _i15.Future>); @override void addListener(_i16.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i16.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } @@ -667,10 +497,7 @@ class MockNutritionPlansProvider extends _i1.Mock @override set database(_i9.IngredientDatabase? _database) => super.noSuchMethod( - Invocation.setter( - #database, - _database, - ), + Invocation.setter(#database, _database), returnValueForMissingStub: null, ); @@ -682,10 +509,7 @@ class MockNutritionPlansProvider extends _i1.Mock @override set ingredients(List<_i13.Ingredient>? _ingredients) => super.noSuchMethod( - Invocation.setter( - #ingredients, - _ingredients, - ), + Invocation.setter(#ingredients, _ingredients), returnValueForMissingStub: null, ); @@ -696,57 +520,40 @@ class MockNutritionPlansProvider extends _i1.Mock ) as List<_i10.NutritionalPlan>); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i10.NutritionalPlan findById(int? id) => (super.noSuchMethod( - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), returnValue: _FakeNutritionalPlan_8( this, - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), ), ) as _i10.NutritionalPlan); @override - _i11.Meal? findMealById(int? id) => (super.noSuchMethod(Invocation.method( - #findMealById, - [id], - )) as _i11.Meal?); + _i11.Meal? findMealById(int? id) => + (super.noSuchMethod(Invocation.method(#findMealById, [id])) + as _i11.Meal?); @override _i15.Future fetchAndSetAllPlansSparse() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansSparse, - [], - ), + Invocation.method(#fetchAndSetAllPlansSparse, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override _i15.Future fetchAndSetAllPlansFull() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansFull, - [], - ), + Invocation.method(#fetchAndSetAllPlansFull, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -754,120 +561,73 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i15.Future<_i10.NutritionalPlan> fetchAndSetPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanSparse, - [planId], - ), - returnValue: - _i15.Future<_i10.NutritionalPlan>.value(_FakeNutritionalPlan_8( - this, - Invocation.method( - #fetchAndSetPlanSparse, - [planId], + Invocation.method(#fetchAndSetPlanSparse, [planId]), + returnValue: _i15.Future<_i10.NutritionalPlan>.value( + _FakeNutritionalPlan_8( + this, + Invocation.method(#fetchAndSetPlanSparse, [planId]), ), - )), + ), ) as _i15.Future<_i10.NutritionalPlan>); @override _i15.Future<_i10.NutritionalPlan> fetchAndSetPlanFull(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanFull, - [planId], - ), - returnValue: - _i15.Future<_i10.NutritionalPlan>.value(_FakeNutritionalPlan_8( - this, - Invocation.method( - #fetchAndSetPlanFull, - [planId], + Invocation.method(#fetchAndSetPlanFull, [planId]), + returnValue: _i15.Future<_i10.NutritionalPlan>.value( + _FakeNutritionalPlan_8( + this, + Invocation.method(#fetchAndSetPlanFull, [planId]), ), - )), + ), ) as _i15.Future<_i10.NutritionalPlan>); @override _i15.Future<_i10.NutritionalPlan> addPlan(_i10.NutritionalPlan? planData) => (super.noSuchMethod( - Invocation.method( - #addPlan, - [planData], - ), - returnValue: - _i15.Future<_i10.NutritionalPlan>.value(_FakeNutritionalPlan_8( - this, - Invocation.method( - #addPlan, - [planData], + Invocation.method(#addPlan, [planData]), + returnValue: _i15.Future<_i10.NutritionalPlan>.value( + _FakeNutritionalPlan_8( + this, + Invocation.method(#addPlan, [planData]), ), - )), + ), ) as _i15.Future<_i10.NutritionalPlan>); @override _i15.Future editPlan(_i10.NutritionalPlan? plan) => (super.noSuchMethod( - Invocation.method( - #editPlan, - [plan], - ), + Invocation.method(#editPlan, [plan]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override _i15.Future deletePlan(int? id) => (super.noSuchMethod( - Invocation.method( - #deletePlan, - [id], - ), + Invocation.method(#deletePlan, [id]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override - _i15.Future<_i11.Meal> addMeal( - _i11.Meal? meal, - int? planId, - ) => + _i15.Future<_i11.Meal> addMeal(_i11.Meal? meal, int? planId) => (super.noSuchMethod( - Invocation.method( - #addMeal, - [ - meal, - planId, - ], + Invocation.method(#addMeal, [meal, planId]), + returnValue: _i15.Future<_i11.Meal>.value( + _FakeMeal_9(this, Invocation.method(#addMeal, [meal, planId])), ), - returnValue: _i15.Future<_i11.Meal>.value(_FakeMeal_9( - this, - Invocation.method( - #addMeal, - [ - meal, - planId, - ], - ), - )), ) as _i15.Future<_i11.Meal>); @override _i15.Future<_i11.Meal> editMeal(_i11.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #editMeal, - [meal], + Invocation.method(#editMeal, [meal]), + returnValue: _i15.Future<_i11.Meal>.value( + _FakeMeal_9(this, Invocation.method(#editMeal, [meal])), ), - returnValue: _i15.Future<_i11.Meal>.value(_FakeMeal_9( - this, - Invocation.method( - #editMeal, - [meal], - ), - )), ) as _i15.Future<_i11.Meal>); @override _i15.Future deleteMeal(_i11.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #deleteMeal, - [meal], - ), + Invocation.method(#deleteMeal, [meal]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -878,42 +638,26 @@ class MockNutritionPlansProvider extends _i1.Mock _i11.Meal? meal, ) => (super.noSuchMethod( - Invocation.method( - #addMealItem, - [ - mealItem, - meal, - ], - ), - returnValue: _i15.Future<_i12.MealItem>.value(_FakeMealItem_10( - this, - Invocation.method( - #addMealItem, - [ - mealItem, - meal, - ], + Invocation.method(#addMealItem, [mealItem, meal]), + returnValue: _i15.Future<_i12.MealItem>.value( + _FakeMealItem_10( + this, + Invocation.method(#addMealItem, [mealItem, meal]), ), - )), + ), ) as _i15.Future<_i12.MealItem>); @override _i15.Future deleteMealItem(_i12.MealItem? mealItem) => (super.noSuchMethod( - Invocation.method( - #deleteMealItem, - [mealItem], - ), + Invocation.method(#deleteMealItem, [mealItem]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override _i15.Future clearIngredientCache() => (super.noSuchMethod( - Invocation.method( - #clearIngredientCache, - [], - ), + Invocation.method(#clearIngredientCache, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -929,22 +673,21 @@ class MockNutritionPlansProvider extends _i1.Mock [ingredientId], {#database: database}, ), - returnValue: _i15.Future<_i13.Ingredient>.value(_FakeIngredient_11( - this, - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, + returnValue: _i15.Future<_i13.Ingredient>.value( + _FakeIngredient_11( + this, + Invocation.method( + #fetchIngredient, + [ingredientId], + {#database: database}, + ), ), - )), + ), ) as _i15.Future<_i13.Ingredient>); @override _i15.Future fetchIngredientsFromCache() => (super.noSuchMethod( - Invocation.method( - #fetchIngredientsFromCache, - [], - ), + Invocation.method(#fetchIngredientsFromCache, []), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -952,38 +695,30 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i15.Future> searchIngredient( String? name, { - String? languageCode = r'en', + String? languageCode = 'en', bool? searchEnglish = false, }) => (super.noSuchMethod( Invocation.method( #searchIngredient, [name], - { - #languageCode: languageCode, - #searchEnglish: searchEnglish, - }, + {#languageCode: languageCode, #searchEnglish: searchEnglish}, ), returnValue: _i15.Future>.value( - <_i18.IngredientApiSearchEntry>[]), + <_i18.IngredientApiSearchEntry>[], + ), ) as _i15.Future>); @override _i15.Future<_i13.Ingredient?> searchIngredientWithCode(String? code) => (super.noSuchMethod( - Invocation.method( - #searchIngredientWithCode, - [code], - ), + Invocation.method(#searchIngredientWithCode, [code]), returnValue: _i15.Future<_i13.Ingredient?>.value(), ) as _i15.Future<_i13.Ingredient?>); @override _i15.Future logMealToDiary(_i11.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #logMealToDiary, - [meal], - ), + Invocation.method(#logMealToDiary, [meal]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -995,31 +730,18 @@ class MockNutritionPlansProvider extends _i1.Mock DateTime? dateTime, ]) => (super.noSuchMethod( - Invocation.method( - #logIngredientToDiary, - [ - mealItem, - planId, - dateTime, - ], - ), + Invocation.method(#logIngredientToDiary, [ + mealItem, + planId, + dateTime, + ]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override - _i15.Future deleteLog( - int? logId, - int? planId, - ) => - (super.noSuchMethod( - Invocation.method( - #deleteLog, - [ - logId, - planId, - ], - ), + _i15.Future deleteLog(int? logId, int? planId) => (super.noSuchMethod( + Invocation.method(#deleteLog, [logId, planId]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @@ -1027,47 +749,32 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i15.Future fetchAndSetLogs(_i10.NutritionalPlan? plan) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetLogs, - [plan], - ), + Invocation.method(#fetchAndSetLogs, [plan]), returnValue: _i15.Future.value(), returnValueForMissingStub: _i15.Future.value(), ) as _i15.Future); @override void addListener(_i16.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i16.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/exercises/contribute_exercise_test.dart b/test/exercises/contribute_exercise_test.dart index b1c595ab0..5e56cc00d 100644 --- a/test/exercises/contribute_exercise_test.dart +++ b/test/exercises/contribute_exercise_test.dart @@ -41,9 +41,12 @@ void main() { Widget createExerciseScreen({locale = 'en'}) { return MultiProvider( providers: [ - ChangeNotifierProvider(create: (context) => mockExerciseProvider), - ChangeNotifierProvider(create: (context) => mockAddExerciseProvider), - ChangeNotifierProvider(create: (context) => mockUserProvider), + ChangeNotifierProvider( + create: (context) => mockExerciseProvider), + ChangeNotifierProvider( + create: (context) => mockAddExerciseProvider), + ChangeNotifierProvider( + create: (context) => mockUserProvider), ], child: MaterialApp( locale: Locale(locale), @@ -54,7 +57,8 @@ void main() { ); } - testWidgets('Unverified users see an info widget', (WidgetTester tester) async { + testWidgets('Unverified users see an info widget', + (WidgetTester tester) async { // Arrange tProfile1.isTrustworthy = false; when(mockUserProvider.profile).thenReturn(tProfile1); @@ -67,7 +71,8 @@ void main() { expect(find.byType(AddExerciseStepper), findsNothing); }); - testWidgets('Verified users see the stepper to add exercises', (WidgetTester tester) async { + testWidgets('Verified users see the stepper to add exercises', + (WidgetTester tester) async { // Arrange tProfile1.isTrustworthy = true; when(mockUserProvider.profile).thenReturn(tProfile1); diff --git a/test/exercises/contribute_exercise_test.mocks.dart b/test/exercises/contribute_exercise_test.mocks.dart index 6b7eba525..ab9194eaa 100644 --- a/test/exercises/contribute_exercise_test.mocks.dart +++ b/test/exercises/contribute_exercise_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/exercises/contribute_exercise_test.dart. // Do not manually edit this file. @@ -29,6 +29,7 @@ import 'package:wger/providers/user.dart' as _i15; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -36,53 +37,28 @@ import 'package:wger/providers/user.dart' as _i15; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExercise_1 extends _i1.SmartFake implements _i3.Exercise { - _FakeExercise_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeExercise_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeTranslation_2 extends _i1.SmartFake implements _i4.Translation { - _FakeTranslation_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeTranslation_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeVariation_3 extends _i1.SmartFake implements _i5.Variation { - _FakeVariation_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeVariation_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAlias_4 extends _i1.SmartFake implements _i6.Alias { - _FakeAlias_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAlias_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [AddExerciseProvider]. @@ -105,19 +81,13 @@ class MockAddExerciseProvider extends _i1.Mock @override set language(_i8.Language? _language) => super.noSuchMethod( - Invocation.setter( - #language, - _language, - ), + Invocation.setter(#language, _language), returnValueForMissingStub: null, ); @override set category(_i9.ExerciseCategory? _category) => super.noSuchMethod( - Invocation.setter( - #category, - _category, - ), + Invocation.setter(#category, _category), returnValueForMissingStub: null, ); @@ -129,64 +99,43 @@ class MockAddExerciseProvider extends _i1.Mock @override set exerciseNameEn(String? name) => super.noSuchMethod( - Invocation.setter( - #exerciseNameEn, - name, - ), + Invocation.setter(#exerciseNameEn, name), returnValueForMissingStub: null, ); @override set exerciseNameTrans(String? name) => super.noSuchMethod( - Invocation.setter( - #exerciseNameTrans, - name, - ), + Invocation.setter(#exerciseNameTrans, name), returnValueForMissingStub: null, ); @override set descriptionEn(String? description) => super.noSuchMethod( - Invocation.setter( - #descriptionEn, - description, - ), + Invocation.setter(#descriptionEn, description), returnValueForMissingStub: null, ); @override set descriptionTrans(String? description) => super.noSuchMethod( - Invocation.setter( - #descriptionTrans, - description, - ), + Invocation.setter(#descriptionTrans, description), returnValueForMissingStub: null, ); @override set alternateNamesEn(List? names) => super.noSuchMethod( - Invocation.setter( - #alternateNamesEn, - names, - ), + Invocation.setter(#alternateNamesEn, names), returnValueForMissingStub: null, ); @override set alternateNamesTrans(List? names) => super.noSuchMethod( - Invocation.setter( - #alternateNamesTrans, - names, - ), + Invocation.setter(#alternateNamesTrans, names), returnValueForMissingStub: null, ); @override set equipment(List<_i11.Equipment>? equipment) => super.noSuchMethod( - Invocation.setter( - #equipment, - equipment, - ), + Invocation.setter(#equipment, equipment), returnValueForMissingStub: null, ); @@ -197,36 +146,26 @@ class MockAddExerciseProvider extends _i1.Mock ) as List<_i11.Equipment>); @override - bool get newVariation => (super.noSuchMethod( - Invocation.getter(#newVariation), - returnValue: false, - ) as bool); + bool get newVariation => + (super.noSuchMethod(Invocation.getter(#newVariation), returnValue: false) + as bool); @override set newVariationForExercise(int? value) => super.noSuchMethod( - Invocation.setter( - #newVariationForExercise, - value, - ), + Invocation.setter(#newVariationForExercise, value), returnValueForMissingStub: null, ); @override set variationId(int? variation) => super.noSuchMethod( - Invocation.setter( - #variationId, - variation, - ), + Invocation.setter(#variationId, variation), returnValueForMissingStub: null, ); @override _i3.Exercise get exercise => (super.noSuchMethod( Invocation.getter(#exercise), - returnValue: _FakeExercise_1( - this, - Invocation.getter(#exercise), - ), + returnValue: _FakeExercise_1(this, Invocation.getter(#exercise)), ) as _i3.Exercise); @override @@ -250,10 +189,7 @@ class MockAddExerciseProvider extends _i1.Mock @override _i5.Variation get variation => (super.noSuchMethod( Invocation.getter(#variation), - returnValue: _FakeVariation_3( - this, - Invocation.getter(#variation), - ), + returnValue: _FakeVariation_3(this, Invocation.getter(#variation)), ) as _i5.Variation); @override @@ -264,10 +200,7 @@ class MockAddExerciseProvider extends _i1.Mock @override set primaryMuscles(List<_i12.Muscle>? muscles) => super.noSuchMethod( - Invocation.setter( - #primaryMuscles, - muscles, - ), + Invocation.setter(#primaryMuscles, muscles), returnValueForMissingStub: null, ); @@ -279,179 +212,115 @@ class MockAddExerciseProvider extends _i1.Mock @override set secondaryMuscles(List<_i12.Muscle>? muscles) => super.noSuchMethod( - Invocation.setter( - #secondaryMuscles, - muscles, - ), + Invocation.setter(#secondaryMuscles, muscles), returnValueForMissingStub: null, ); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override void addExerciseImages(List<_i10.File>? exercises) => super.noSuchMethod( - Invocation.method( - #addExerciseImages, - [exercises], - ), + Invocation.method(#addExerciseImages, [exercises]), returnValueForMissingStub: null, ); @override void removeExercise(String? path) => super.noSuchMethod( - Invocation.method( - #removeExercise, - [path], - ), + Invocation.method(#removeExercise, [path]), returnValueForMissingStub: null, ); @override void printValues() => super.noSuchMethod( - Invocation.method( - #printValues, - [], - ), + Invocation.method(#printValues, []), returnValueForMissingStub: null, ); @override _i13.Future addExercise() => (super.noSuchMethod( - Invocation.method( - #addExercise, - [], - ), + Invocation.method(#addExercise, []), returnValue: _i13.Future.value(0), ) as _i13.Future); @override _i13.Future<_i3.Exercise> addExerciseBase() => (super.noSuchMethod( - Invocation.method( - #addExerciseBase, - [], + Invocation.method(#addExerciseBase, []), + returnValue: _i13.Future<_i3.Exercise>.value( + _FakeExercise_1(this, Invocation.method(#addExerciseBase, [])), ), - returnValue: _i13.Future<_i3.Exercise>.value(_FakeExercise_1( - this, - Invocation.method( - #addExerciseBase, - [], - ), - )), ) as _i13.Future<_i3.Exercise>); @override _i13.Future<_i5.Variation> addVariation() => (super.noSuchMethod( - Invocation.method( - #addVariation, - [], + Invocation.method(#addVariation, []), + returnValue: _i13.Future<_i5.Variation>.value( + _FakeVariation_3(this, Invocation.method(#addVariation, [])), ), - returnValue: _i13.Future<_i5.Variation>.value(_FakeVariation_3( - this, - Invocation.method( - #addVariation, - [], - ), - )), ) as _i13.Future<_i5.Variation>); @override _i13.Future addImages(_i3.Exercise? base) => (super.noSuchMethod( - Invocation.method( - #addImages, - [base], - ), + Invocation.method(#addImages, [base]), returnValue: _i13.Future.value(), returnValueForMissingStub: _i13.Future.value(), ) as _i13.Future); @override _i13.Future<_i4.Translation> addExerciseTranslation( - _i4.Translation? exercise) => + _i4.Translation? exercise, + ) => (super.noSuchMethod( - Invocation.method( - #addExerciseTranslation, - [exercise], - ), - returnValue: _i13.Future<_i4.Translation>.value(_FakeTranslation_2( - this, - Invocation.method( - #addExerciseTranslation, - [exercise], + Invocation.method(#addExerciseTranslation, [exercise]), + returnValue: _i13.Future<_i4.Translation>.value( + _FakeTranslation_2( + this, + Invocation.method(#addExerciseTranslation, [exercise]), ), - )), + ), ) as _i13.Future<_i4.Translation>); @override - _i13.Future<_i6.Alias> addExerciseAlias( - String? name, - int? exerciseId, - ) => + _i13.Future<_i6.Alias> addExerciseAlias(String? name, int? exerciseId) => (super.noSuchMethod( - Invocation.method( - #addExerciseAlias, - [ - name, - exerciseId, - ], - ), - returnValue: _i13.Future<_i6.Alias>.value(_FakeAlias_4( - this, - Invocation.method( - #addExerciseAlias, - [ - name, - exerciseId, - ], + Invocation.method(#addExerciseAlias, [name, exerciseId]), + returnValue: _i13.Future<_i6.Alias>.value( + _FakeAlias_4( + this, + Invocation.method(#addExerciseAlias, [name, exerciseId]), ), - )), + ), ) as _i13.Future<_i6.Alias>); @override void addListener(_i14.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i14.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } @@ -475,91 +344,63 @@ class MockUserProvider extends _i1.Mock implements _i15.UserProvider { @override set profile(_i16.Profile? _profile) => super.noSuchMethod( - Invocation.setter( - #profile, - _profile, - ), + Invocation.setter(#profile, _profile), returnValueForMissingStub: null, ); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i13.Future fetchAndSetProfile() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetProfile, - [], - ), + Invocation.method(#fetchAndSetProfile, []), returnValue: _i13.Future.value(), returnValueForMissingStub: _i13.Future.value(), ) as _i13.Future); @override _i13.Future saveProfile() => (super.noSuchMethod( - Invocation.method( - #saveProfile, - [], - ), + Invocation.method(#saveProfile, []), returnValue: _i13.Future.value(), returnValueForMissingStub: _i13.Future.value(), ) as _i13.Future); @override _i13.Future verifyEmail() => (super.noSuchMethod( - Invocation.method( - #verifyEmail, - [], - ), + Invocation.method(#verifyEmail, []), returnValue: _i13.Future.value(), returnValueForMissingStub: _i13.Future.value(), ) as _i13.Future); @override void addListener(_i14.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i14.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/exercises/exercise_provider_db_test.dart b/test/exercises/exercise_provider_db_test.dart index d110749d9..13e34a657 100644 --- a/test/exercises/exercise_provider_db_test.dart +++ b/test/exercises/exercise_provider_db_test.dart @@ -63,9 +63,12 @@ void main() { path: 'api/v2/$languageUrl/', ); - const muscle1 = Muscle(id: 1, name: 'Biceps brachii', nameEn: 'Biceps', isFront: true); - const muscle2 = Muscle(id: 2, name: 'Anterior deltoid', nameEn: 'Biceps', isFront: true); - const muscle3 = Muscle(id: 4, name: 'Biceps femoris', nameEn: 'Hamstrings', isFront: false); + const muscle1 = + Muscle(id: 1, name: 'Biceps brachii', nameEn: 'Biceps', isFront: true); + const muscle2 = + Muscle(id: 2, name: 'Anterior deltoid', nameEn: 'Biceps', isFront: true); + const muscle3 = Muscle( + id: 4, name: 'Biceps femoris', nameEn: 'Hamstrings', isFront: false); final Map tCategoryMap = jsonDecode( fixture('exercises/category_entries.json'), @@ -106,7 +109,8 @@ void main() { .thenAnswer((_) => Future.value(tMuscleMap['results'])); // Mock equipment - when(mockBaseProvider.makeUrl(equipmentUrl)).thenReturn(tEquipmentEntriesUri); + when(mockBaseProvider.makeUrl(equipmentUrl)) + .thenReturn(tEquipmentEntriesUri); when(mockBaseProvider.fetchPaginated(tEquipmentEntriesUri)) .thenAnswer((_) => Future.value(tEquipmentMap['results'])); @@ -118,12 +122,14 @@ void main() { ); // Mock base info response - when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl)).thenReturn(tExerciseInfoUri); + when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl)) + .thenReturn(tExerciseInfoUri); when(mockBaseProvider.fetch(tExerciseInfoUri)).thenAnswer( (_) => Future.value(tExerciseBaseInfoMap), ); - when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl, id: 9)).thenReturn(tExerciseInfoDetailUri); + when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl, id: 9)) + .thenReturn(tExerciseInfoDetailUri); when(mockBaseProvider.fetch(tExerciseInfoDetailUri)).thenAnswer( (_) => Future.value(tExerciseBaseInfoMap), ); @@ -143,8 +149,10 @@ void main() { await provider.fetchAndSetMuscles(database); // Assert - final updateTime = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_MUSCLES)!); - final valid = DateTime.now().add(const Duration(days: ExercisesProvider.EXERCISE_CACHE_DAYS)); + final updateTime = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_MUSCLES)!); + final valid = DateTime.now() + .add(const Duration(days: ExercisesProvider.EXERCISE_CACHE_DAYS)); expect(updateTime.isSameDayAs(valid), true); final muscles = await database.select(database.muscles).get(); @@ -166,7 +174,8 @@ void main() { expect(provider.muscles[2], muscle3); }); - test('that if there is already valid data in the DB, the API is not hit', () async { + test('that if there is already valid data in the DB, the API is not hit', + () async { // Arrange final prefs = await SharedPreferences.getInstance(); await provider.initCacheTimesLocalPrefs(); @@ -185,7 +194,8 @@ void main() { await provider.fetchAndSetMuscles(database); // Assert - final updateTime = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_MUSCLES)!); + final updateTime = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_MUSCLES)!); expect(updateTime.isSameDayAs(valid), true); expect(provider.muscles.length, 2); @@ -206,8 +216,10 @@ void main() { await provider.fetchAndSetLanguages(database); // Assert - final updateTime = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_LANGUAGES)!); - final valid = DateTime.now().add(const Duration(days: ExercisesProvider.EXERCISE_CACHE_DAYS)); + final updateTime = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_LANGUAGES)!); + final valid = DateTime.now() + .add(const Duration(days: ExercisesProvider.EXERCISE_CACHE_DAYS)); expect(updateTime.isSameDayAs(valid), true); final languages = await database.select(database.languages).get(); @@ -233,7 +245,8 @@ void main() { expect(provider.languages[3], tLanguage3); }); - test('that if there is already valid data in the DB, the API is not hit', () async { + test('that if there is already valid data in the DB, the API is not hit', + () async { // Arrange final prefs = await SharedPreferences.getInstance(); await provider.initCacheTimesLocalPrefs(); @@ -241,18 +254,17 @@ void main() { final valid = DateTime.now().add(const Duration(days: 1)); prefs.setString(PREFS_LAST_UPDATED_LANGUAGES, valid.toIso8601String()); - await database - .into(database.languages) - .insert(LanguagesCompanion.insert(id: tLanguage1.id, data: tLanguage1)); - await database - .into(database.languages) - .insert(LanguagesCompanion.insert(id: tLanguage2.id, data: tLanguage2)); + await database.into(database.languages).insert( + LanguagesCompanion.insert(id: tLanguage1.id, data: tLanguage1)); + await database.into(database.languages).insert( + LanguagesCompanion.insert(id: tLanguage2.id, data: tLanguage2)); // Act await provider.fetchAndSetLanguages(database); // Assert - final updateTime = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_LANGUAGES)!); + final updateTime = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_LANGUAGES)!); expect(updateTime.isSameDayAs(valid), true); expect(provider.languages.length, 2); @@ -272,8 +284,10 @@ void main() { await provider.fetchAndSetCategories(database); // Assert - final updateTime = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_CATEGORIES)!); - final valid = DateTime.now().add(const Duration(days: ExercisesProvider.EXERCISE_CACHE_DAYS)); + final updateTime = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_CATEGORIES)!); + final valid = DateTime.now() + .add(const Duration(days: ExercisesProvider.EXERCISE_CACHE_DAYS)); expect(updateTime.isSameDayAs(valid), true); final categories = await database.select(database.categories).get(); @@ -291,7 +305,8 @@ void main() { expect(provider.categories[1], tCategory2); }); - test('that if there is already valid data in the DB, the API is not hit', () async { + test('that if there is already valid data in the DB, the API is not hit', + () async { // Arrange final prefs = await SharedPreferences.getInstance(); await provider.initCacheTimesLocalPrefs(); @@ -299,18 +314,17 @@ void main() { final valid = DateTime.now().add(const Duration(days: 1)); prefs.setString(PREFS_LAST_UPDATED_CATEGORIES, valid.toIso8601String()); - await database - .into(database.categories) - .insert(CategoriesCompanion.insert(id: tCategory1.id, data: tCategory1)); - await database - .into(database.categories) - .insert(CategoriesCompanion.insert(id: tCategory2.id, data: tCategory2)); + await database.into(database.categories).insert( + CategoriesCompanion.insert(id: tCategory1.id, data: tCategory1)); + await database.into(database.categories).insert( + CategoriesCompanion.insert(id: tCategory2.id, data: tCategory2)); // Act await provider.fetchAndSetCategories(database); // Assert - final updateTime = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_CATEGORIES)!); + final updateTime = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_CATEGORIES)!); expect(updateTime.isSameDayAs(valid), true); expect(provider.categories.length, 2); @@ -331,8 +345,10 @@ void main() { await provider.fetchAndSetEquipments(database); // Assert - final updateTime = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_EQUIPMENT)!); - final valid = DateTime.now().add(const Duration(days: ExercisesProvider.EXERCISE_CACHE_DAYS)); + final updateTime = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_EQUIPMENT)!); + final valid = DateTime.now() + .add(const Duration(days: ExercisesProvider.EXERCISE_CACHE_DAYS)); expect(updateTime.isSameDayAs(valid), true); final equipmentList = await database.select(database.equipments).get(); @@ -352,7 +368,8 @@ void main() { expect(provider.equipment[3], tEquipment4); }); - test('that if there is already valid data in the DB, the API is not hit', () async { + test('that if there is already valid data in the DB, the API is not hit', + () async { // Arrange final prefs = await SharedPreferences.getInstance(); await provider.initCacheTimesLocalPrefs(); @@ -360,18 +377,17 @@ void main() { final valid = DateTime.now().add(const Duration(days: 1)); prefs.setString(PREFS_LAST_UPDATED_EQUIPMENT, valid.toIso8601String()); - await database - .into(database.equipments) - .insert(EquipmentsCompanion.insert(id: tEquipment1.id, data: tEquipment1)); - await database - .into(database.equipments) - .insert(EquipmentsCompanion.insert(id: tCategory2.id, data: tEquipment2)); + await database.into(database.equipments).insert( + EquipmentsCompanion.insert(id: tEquipment1.id, data: tEquipment1)); + await database.into(database.equipments).insert( + EquipmentsCompanion.insert(id: tCategory2.id, data: tEquipment2)); // Act await provider.fetchAndSetEquipments(database); // Assert - final updateTime = DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_EQUIPMENT)!); + final updateTime = + DateTime.parse(prefs.getString(PREFS_LAST_UPDATED_EQUIPMENT)!); expect(updateTime.isSameDayAs(valid), true); expect(provider.equipment.length, 2); @@ -383,7 +399,8 @@ void main() { }); group('Exercise cache DB', () { - test('that if there is already valid data in the DB, the API is not hit', () async { + test('that if there is already valid data in the DB, the API is not hit', + () async { // Arrange final prefs = await SharedPreferences.getInstance(); await provider.initCacheTimesLocalPrefs(); @@ -394,19 +411,17 @@ void main() { ExercisesCompanion.insert( id: tExerciseBaseInfoMap['id'], data: json.encode(tExerciseBaseInfoMap), - lastUpdate: DateTime.parse(tExerciseBaseInfoMap['last_update_global']), + lastUpdate: + DateTime.parse(tExerciseBaseInfoMap['last_update_global']), lastFetched: DateTime.now(), ), ); - await database - .into(database.languages) - .insert(LanguagesCompanion.insert(id: tLanguage1.id, data: tLanguage1)); - await database - .into(database.languages) - .insert(LanguagesCompanion.insert(id: tLanguage2.id, data: tLanguage2)); - await database - .into(database.languages) - .insert(LanguagesCompanion.insert(id: tLanguage3.id, data: tLanguage3)); + await database.into(database.languages).insert( + LanguagesCompanion.insert(id: tLanguage1.id, data: tLanguage1)); + await database.into(database.languages).insert( + LanguagesCompanion.insert(id: tLanguage2.id, data: tLanguage2)); + await database.into(database.languages).insert( + LanguagesCompanion.insert(id: tLanguage3.id, data: tLanguage3)); // Act await provider.fetchAndSetLanguages(database); @@ -415,7 +430,8 @@ void main() { // Assert expect(provider.exercises.length, 1); expect(provider.exercises.first.id, 9); - expect(provider.exercises.first.uuid, '1b020b3a-3732-4c7e-92fd-a0cec90ed69b'); + expect(provider.exercises.first.uuid, + '1b020b3a-3732-4c7e-92fd-a0cec90ed69b'); verifyNever(mockBaseProvider.fetchPaginated(any)); }); @@ -426,7 +442,8 @@ void main() { ExercisesCompanion.insert( id: tExerciseBaseInfoMap['id'], data: json.encode(tExerciseBaseInfoMap), - lastUpdate: DateTime.parse(tExerciseBaseInfoMap['last_update_global']), + lastUpdate: + DateTime.parse(tExerciseBaseInfoMap['last_update_global']), lastFetched: DateTime.now().subtract(const Duration(hours: 1)), ), ); @@ -440,18 +457,21 @@ void main() { // Assert expect(provider.exercises.length, 1); expect(provider.exercises.first.id, 9); - expect(provider.exercises.first.uuid, '1b020b3a-3732-4c7e-92fd-a0cec90ed69b'); + expect(provider.exercises.first.uuid, + '1b020b3a-3732-4c7e-92fd-a0cec90ed69b'); verifyNever(mockBaseProvider.fetch(any)); }); - test('fetching a known exercise - needed API refresh - no new data', () async { + test('fetching a known exercise - needed API refresh - no new data', + () async { // Arrange provider.languages = testLanguages; await database.into(database.exercises).insert( ExercisesCompanion.insert( id: tExerciseBaseInfoMap['id'], data: json.encode(tExerciseBaseInfoMap), - lastUpdate: DateTime.parse(tExerciseBaseInfoMap['last_update_global']), + lastUpdate: + DateTime.parse(tExerciseBaseInfoMap['last_update_global']), lastFetched: DateTime.now().subtract(const Duration(days: 10)), ), ); @@ -461,18 +481,21 @@ void main() { // Act await provider.handleUpdateExerciseFromApi(database, 9); - final exerciseDb = await (database.select(database.exercises)..where((e) => e.id.equals(9))) + final exerciseDb = await (database.select(database.exercises) + ..where((e) => e.id.equals(9))) .getSingleOrNull(); // Assert verify(mockBaseProvider.fetch(any)); expect(provider.exercises.length, 1); expect(provider.exercises.first.id, 9); - expect(provider.exercises.first.uuid, '1b020b3a-3732-4c7e-92fd-a0cec90ed69b'); + expect(provider.exercises.first.uuid, + '1b020b3a-3732-4c7e-92fd-a0cec90ed69b'); expect(exerciseDb!.lastFetched.isSameDayAs(DateTime.now()), true); }); - test('fetching a known exercise - needed API refresh - new data from API', () async { + test('fetching a known exercise - needed API refresh - new data from API', + () async { // Arrange provider.languages = testLanguages; final newData = Map.from(tExerciseBaseInfoMap); @@ -492,7 +515,8 @@ void main() { // Act await provider.handleUpdateExerciseFromApi(database, 9); - final exerciseDb = await (database.select(database.exercises)..where((e) => e.id.equals(9))) + final exerciseDb = await (database.select(database.exercises) + ..where((e) => e.id.equals(9))) .getSingleOrNull(); final exerciseData = ExerciseApiData.fromString(exerciseDb!.data); @@ -500,7 +524,8 @@ void main() { verify(mockBaseProvider.fetch(any)); expect(provider.exercises.length, 1); expect(provider.exercises.first.id, 9); - expect(provider.exercises.first.uuid, '1b020b3a-3732-4c7e-92fd-a0cec90ed69b'); + expect(provider.exercises.first.uuid, + '1b020b3a-3732-4c7e-92fd-a0cec90ed69b'); expect(exerciseDb.lastFetched.isSameDayAs(DateTime.now()), true); expect(exerciseData.uuid, '1b020b3a-3732-4c7e-92fd-a0cec90ed69b'); }); diff --git a/test/exercises/exercise_provider_load_test.dart b/test/exercises/exercise_provider_load_test.dart index 7123cba76..b4edaba51 100644 --- a/test/exercises/exercise_provider_load_test.dart +++ b/test/exercises/exercise_provider_load_test.dart @@ -54,8 +54,10 @@ void main() { provider.languages = [tLanguage1, tLanguage2, tLanguage3]; // Mock base info response - when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl, id: 9)).thenReturn(tExerciseBaseInfoUri); - when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl, id: 1)).thenReturn(tExerciseBaseInfoUri2); + when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl, id: 9)) + .thenReturn(tExerciseBaseInfoUri); + when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl, id: 1)) + .thenReturn(tExerciseBaseInfoUri2); when(mockBaseProvider.fetch(tExerciseBaseInfoUri)) .thenAnswer((_) => Future.value(tExerciseInfoMap)); @@ -112,13 +114,16 @@ void main() { 'd8aa5990-bb47-4111-9823-e2fbd98fe07f', '49a159e1-1e00-409a-81c9-b4d4489fbd67', ]); - expect(exercise.videos.map((v) => v.uuid), ['63e996e9-a772-4ca5-9d09-8b4be03f6be4']); + expect(exercise.videos.map((v) => v.uuid), + ['63e996e9-a772-4ca5-9d09-8b4be03f6be4']); final translation1 = exercise.translations[0]; expect(translation1.name, '2 Handed Kettlebell Swing'); - expect(translation1.languageObj.shortName, 'en'); - expect(translation1.notes[0].comment, "it's important to do the exercise correctly"); - expect(translation1.notes[1].comment, 'put a lot of effort into this exercise'); + expect(translation1.languageObj?.shortName, 'en'); + expect(translation1.notes[0].comment, + "it's important to do the exercise correctly"); + expect(translation1.notes[1].comment, + 'put a lot of effort into this exercise'); expect(translation1.notes[2].comment, 'have fun'); expect(translation1.aliases[0].alias, 'double handed kettlebell'); expect(translation1.aliases[1].alias, 'Kettlebell russian style'); diff --git a/test/exercises/exercise_provider_test.dart b/test/exercises/exercise_provider_test.dart index 5a24bf439..4cac25ecc 100644 --- a/test/exercises/exercise_provider_test.dart +++ b/test/exercises/exercise_provider_test.dart @@ -66,7 +66,8 @@ void main() { ); const category1 = ExerciseCategory(id: 1, name: 'Arms'); - const muscle1 = Muscle(id: 1, name: 'Biceps brachii', nameEn: 'Biceps', isFront: true); + const muscle1 = + Muscle(id: 1, name: 'Biceps brachii', nameEn: 'Biceps', isFront: true); final Map tCategoryMap = jsonDecode( fixture('exercises/category_entries.json'), @@ -111,7 +112,8 @@ void main() { .thenAnswer((_) => Future.value(tMuscleMap['results'])); // Mock equipment - when(mockBaseProvider.makeUrl(equipmentUrl)).thenReturn(tEquipmentEntriesUri); + when(mockBaseProvider.makeUrl(equipmentUrl)) + .thenReturn(tEquipmentEntriesUri); when(mockBaseProvider.fetchPaginated(tEquipmentEntriesUri)) .thenAnswer((_) => Future.value(tEquipmentMap['results'])); @@ -122,8 +124,10 @@ void main() { .thenAnswer((_) => Future.value(tLanguageMap['results'])); // Mock base info response - when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl, id: 1)).thenReturn(tExerciseInfoUri); - when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl, id: 2)).thenReturn(tExerciseInfoUri); + when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl, id: 1)) + .thenReturn(tExerciseInfoUri); + when(mockBaseProvider.makeUrl(exerciseBaseInfoUrl, id: 2)) + .thenReturn(tExerciseInfoUri); when(mockBaseProvider.fetch(tExerciseInfoUri)) .thenAnswer((_) => Future.value(tExerciseBaseInfoMap)); }); @@ -142,7 +146,8 @@ void main() { test('should throw a NoResultException if no category is found', () { // act & assert - expect(() => provider.findCategoryById(3), throwsA(isA())); + expect(() => provider.findCategoryById(3), + throwsA(isA())); }); }); @@ -160,7 +165,8 @@ void main() { test('should throw a NoResultException if no muscle is found', () { // act & assert - expect(() => provider.findMuscleById(3), throwsA(isA())); + expect(() => provider.findMuscleById(3), + throwsA(isA())); }); }); @@ -178,7 +184,8 @@ void main() { test('should throw a NoResultException if no equipment is found', () { // act & assert - expect(() => provider.findEquipmentById(10), throwsA(isA())); + expect(() => provider.findEquipmentById(10), + throwsA(isA())); }); }); @@ -196,7 +203,8 @@ void main() { test('should throw a NoResultException if no equipment is found', () { // act & assert - expect(() => provider.findLanguageById(10), throwsA(isA())); + expect(() => provider.findLanguageById(10), + throwsA(isA())); }); }); @@ -219,7 +227,8 @@ void main() { SharedPreferences.setMockInitialValues({}); filters = Filters( - exerciseCategories: FilterCategory(title: 'Muscle Groups', items: {}), + exerciseCategories: FilterCategory( + title: 'Muscle Groups', items: {}), equipment: FilterCategory(title: 'Equipment', items: {}), ); @@ -239,10 +248,12 @@ void main() { expect(provider.filteredExercises, data.getTestExercises()); }); - test('A muscle is selected with no search term. Should find results', () async { + test('A muscle is selected with no search term. Should find results', + () async { // arrange final Filters tFilters = filters.copyWith( - exerciseCategories: filters.exerciseCategories.copyWith(items: {data.tCategory1: true}), + exerciseCategories: filters.exerciseCategories + .copyWith(items: {data.tCategory1: true}), ); // act @@ -253,10 +264,12 @@ void main() { expect(provider.filteredExercises, [data.getTestExercises()[0]]); }); - test('A muscle is selected with no search term. Should not find results', () async { + test('A muscle is selected with no search term. Should not find results', + () async { // arrange final Filters tFilters = filters.copyWith( - exerciseCategories: filters.exerciseCategories.copyWith(items: {data.tCategory5: true}), + exerciseCategories: filters.exerciseCategories + .copyWith(items: {data.tCategory5: true}), ); // act @@ -267,10 +280,12 @@ void main() { expect(provider.filteredExercises, isEmpty); }); - test('An equipment is selected with no search term. Should find results', () async { + test('An equipment is selected with no search term. Should find results', + () async { // arrange final Filters tFilters = filters.copyWith( - equipment: filters.equipment.copyWith(items: {data.tEquipment1: true}), + equipment: + filters.equipment.copyWith(items: {data.tEquipment1: true}), ); // act @@ -281,10 +296,13 @@ void main() { expect(provider.filteredExercises, [data.getTestExercises()[0]]); }); - test('An equipment is selected with no search term. Should not find results', () async { + test( + 'An equipment is selected with no search term. Should not find results', + () async { // arrange final Filters tFilters = filters.copyWith( - equipment: filters.equipment.copyWith(items: {data.tEquipment3: true}), + equipment: + filters.equipment.copyWith(items: {data.tEquipment3: true}), ); // act @@ -298,8 +316,10 @@ void main() { test('A muscle and equipment is selected and there is a match', () async { // arrange final Filters tFilters = filters.copyWith( - exerciseCategories: filters.exerciseCategories.copyWith(items: {data.tCategory2: true}), - equipment: filters.equipment.copyWith(items: {data.tEquipment2: true}), + exerciseCategories: filters.exerciseCategories + .copyWith(items: {data.tCategory2: true}), + equipment: + filters.equipment.copyWith(items: {data.tEquipment2: true}), ); // act @@ -313,7 +333,8 @@ void main() { test('A muscle and equipment is selected but no match', () async { // arrange final Filters tFilters = filters.copyWith( - exerciseCategories: filters.exerciseCategories.copyWith(items: {data.tCategory2: true}), + exerciseCategories: filters.exerciseCategories + .copyWith(items: {data.tCategory2: true}), equipment: filters.equipment.copyWith(items: {tEquipment1: true}), ); @@ -330,7 +351,10 @@ void main() { setUp(() { const String tSearchTerm = 'press'; const String tSearchLanguage = 'en'; - final Map query = {'term': tSearchTerm, 'language': tSearchLanguage}; + final Map query = { + 'term': tSearchTerm, + 'language': tSearchLanguage + }; tSearchByNameUri = Uri( scheme: 'http', host: 'localhost', @@ -348,7 +372,8 @@ void main() { query: {'term': tSearchTerm, 'language': tSearchLanguage}, ), ).thenReturn(tSearchByNameUri); - when(mockBaseProvider.fetch(tSearchByNameUri)).thenAnswer((_) async => tSearchResponse); + when(mockBaseProvider.fetch(tSearchByNameUri)) + .thenAnswer((_) async => tSearchResponse); }); test('Should find results from search term', () async { @@ -365,11 +390,14 @@ void main() { [data.getTestExercises()[0], data.getTestExercises()[1]], ); }); - test('Should find items from selection but should filter them by search term', () async { + test( + 'Should find items from selection but should filter them by search term', + () async { // arrange final Filters tFilters = filters.copyWith( searchTerm: 'press', - exerciseCategories: filters.exerciseCategories.copyWith(items: {data.tCategory3: true}), + exerciseCategories: filters.exerciseCategories + .copyWith(items: {data.tCategory3: true}), ); // act @@ -384,7 +412,8 @@ void main() { }); group('local prefs', () { - test('initCacheTimesLocalPrefs correctly initalises the cache values', () async { + test('initCacheTimesLocalPrefs correctly initalises the cache values', + () async { // arrange const initValue = '2023-01-01T00:00:00.000'; final prefs = await SharedPreferences.getInstance(); @@ -419,7 +448,8 @@ void main() { expect(prefs.getString(PREFS_LAST_UPDATED_LANGUAGES), newValue); }); - test('calling initCacheTimesLocalPrefs with forceInit replaces the date', () async { + test('calling initCacheTimesLocalPrefs with forceInit replaces the date', + () async { // arrange final prefs = await SharedPreferences.getInstance(); const initValue = '2023-01-01T00:00:00.000'; diff --git a/test/exercises/exercises_detail_widget_test.dart b/test/exercises/exercises_detail_widget_test.dart index d40dd8575..61aacc10c 100644 --- a/test/exercises/exercises_detail_widget_test.dart +++ b/test/exercises/exercises_detail_widget_test.dart @@ -42,7 +42,8 @@ void main() { ); } - testWidgets('Test the widgets on the exercise detail widget', (WidgetTester tester) async { + testWidgets('Test the widgets on the exercise detail widget', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); await tester.pumpAndSettle(); @@ -51,9 +52,12 @@ void main() { expect(find.text('Bench'), findsOneWidget, reason: 'Equipment'); expect(find.text('Dumbbell'), findsOneWidget, reason: 'Equipment'); - expect(find.text('Muscles'), findsNWidgets(2), reason: 'One header, one sub header'); - expect(find.text('Flutterus maximus (Glutes)'), findsOneWidget, reason: 'Muscles'); - expect(find.text('Biceps brachii (Biceps)'), findsOneWidget, reason: 'Muscles'); + expect(find.text('Muscles'), findsNWidgets(2), + reason: 'One header, one sub header'); + expect(find.text('Flutterus maximus (Glutes)'), findsOneWidget, + reason: 'Muscles'); + expect(find.text('Biceps brachii (Biceps)'), findsOneWidget, + reason: 'Muscles'); expect(find.text('Secondary muscles'), findsOneWidget); expect( @@ -61,8 +65,10 @@ void main() { findsNWidgets(2), reason: 'Two diagrams, one for front, one for the back', ); - expect(find.text('Gluteus maximus'), findsOneWidget, reason: 'Secondary muscles'); - expect(find.text('Description'), findsOneWidget, reason: 'Description header'); + expect(find.text('Gluteus maximus'), findsOneWidget, + reason: 'Secondary muscles'); + expect(find.text('Description'), findsOneWidget, + reason: 'Description header'); expect(find.text('add clever text'), findsOneWidget, reason: 'Description'); expect(find.text('Variations'), findsNothing); }); diff --git a/test/exercises/model_exercise_test.dart b/test/exercises/model_exercise_test.dart index 2d817ba0b..ec4e9f670 100644 --- a/test/exercises/model_exercise_test.dart +++ b/test/exercises/model_exercise_test.dart @@ -59,13 +59,16 @@ void main() { 'd8aa5990-bb47-4111-9823-e2fbd98fe07f', '49a159e1-1e00-409a-81c9-b4d4489fbd67', ]); - expect(exercise.videos.map((v) => v.uuid), ['63e996e9-a772-4ca5-9d09-8b4be03f6be4']); + expect(exercise.videos.map((v) => v.uuid), + ['63e996e9-a772-4ca5-9d09-8b4be03f6be4']); final translation1 = exercise.translations[0]; expect(translation1.name, '2 Handed Kettlebell Swing'); - expect(translation1.languageObj.shortName, 'en'); - expect(translation1.notes[0].comment, "it's important to do the exercise correctly"); - expect(translation1.notes[1].comment, 'put a lot of effort into this exercise'); + expect(translation1.languageObj?.shortName, 'en'); + expect(translation1.notes[0].comment, + "it's important to do the exercise correctly"); + expect(translation1.notes[1].comment, + 'put a lot of effort into this exercise'); expect(translation1.notes[2].comment, 'have fun'); expect(translation1.aliases[0].alias, 'double handed kettlebell'); expect(translation1.aliases[1].alias, 'Kettlebell russian style'); diff --git a/test/gallery/gallery_form_test.dart b/test/gallery/gallery_form_test.dart index 6fdc69e01..e48efc996 100644 --- a/test/gallery/gallery_form_test.dart +++ b/test/gallery/gallery_form_test.dart @@ -51,8 +51,10 @@ void main() { ); } - testWidgets('Test opening the form for an existing image', (WidgetTester tester) async { - await mockNetworkImagesFor(() => tester.pumpWidget(createScreen(useImage: true))); + testWidgets('Test opening the form for an existing image', + (WidgetTester tester) async { + await mockNetworkImagesFor( + () => tester.pumpWidget(createScreen(useImage: true))); await tester.pump(); expect(find.byType(TextFormField), findsNWidgets(2)); @@ -72,8 +74,10 @@ void main() { verify(mockGalleryProvider.editImage(any, any)); }); - testWidgets('Test opening the form for a new image', (WidgetTester tester) async { - await mockNetworkImagesFor(() => tester.pumpWidget(createScreen(useImage: false))); + testWidgets('Test opening the form for a new image', + (WidgetTester tester) async { + await mockNetworkImagesFor( + () => tester.pumpWidget(createScreen(useImage: false))); await tester.pumpAndSettle(); expect(find.text('Please select an image'), findsOneWidget); diff --git a/test/gallery/gallery_form_test.mocks.dart b/test/gallery/gallery_form_test.mocks.dart index 4a9db0978..ed69580f3 100644 --- a/test/gallery/gallery_form_test.mocks.dart +++ b/test/gallery/gallery_form_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/gallery/gallery_form_test.dart. // Do not manually edit this file. @@ -21,49 +21,30 @@ import 'package:wger/providers/gallery.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [GalleryProvider]. @@ -82,114 +63,71 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { @override set images(List<_i5.Image>? _images) => super.noSuchMethod( - Invocation.setter( - #images, - _images, - ), + Invocation.setter(#images, _images), returnValueForMissingStub: null, ); @override _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_0( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) as _i2.AuthProvider); @override set auth(_i2.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i6.Future fetchAndSetGallery() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetGallery, - [], - ), + Invocation.method(#fetchAndSetGallery, []), returnValue: _i6.Future.value(), returnValueForMissingStub: _i6.Future.value(), ) as _i6.Future); @override - _i6.Future addImage( - _i5.Image? image, - _i7.XFile? imageFile, - ) => + _i6.Future addImage(_i5.Image? image, _i7.XFile? imageFile) => (super.noSuchMethod( - Invocation.method( - #addImage, - [ - image, - imageFile, - ], - ), + Invocation.method(#addImage, [image, imageFile]), returnValue: _i6.Future.value(), returnValueForMissingStub: _i6.Future.value(), ) as _i6.Future); @override - _i6.Future editImage( - _i5.Image? image, - _i7.XFile? imageFile, - ) => + _i6.Future editImage(_i5.Image? image, _i7.XFile? imageFile) => (super.noSuchMethod( - Invocation.method( - #editImage, - [ - image, - imageFile, - ], - ), + Invocation.method(#editImage, [image, imageFile]), returnValue: _i6.Future.value(), returnValueForMissingStub: _i6.Future.value(), ) as _i6.Future); @override _i6.Future deleteImage(_i5.Image? image) => (super.noSuchMethod( - Invocation.method( - #deleteImage, - [image], - ), + Invocation.method(#deleteImage, [image]), returnValue: _i6.Future.value(), returnValueForMissingStub: _i6.Future.value(), ) as _i6.Future); @@ -197,11 +135,9 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -216,60 +152,39 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i6.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i6.Future>.value( + {}, ), - returnValue: - _i6.Future>.value({}), ) as _i6.Future>); @override _i6.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i6.Future>.value([]), ) as _i6.Future>); @override - _i6.Future> post( - Map? data, - Uri? uri, - ) => + _i6.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i6.Future>.value( + {}, ), - returnValue: - _i6.Future>.value({}), ) as _i6.Future>); @override @@ -278,75 +193,45 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i6.Future>.value( + {}, ), - returnValue: - _i6.Future>.value({}), ) as _i6.Future>); @override - _i6.Future<_i3.Response> deleteRequest( - String? url, - int? id, - ) => + _i6.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i6.Future<_i3.Response>); @override void addListener(_i8.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i8.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/gallery/gallery_provider_test.dart b/test/gallery/gallery_provider_test.dart index b0e067b6b..df0fcc15f 100644 --- a/test/gallery/gallery_provider_test.dart +++ b/test/gallery/gallery_provider_test.dart @@ -71,7 +71,8 @@ void main() { final image = gallery.Image( id: 58, date: DateTime(2022, 01, 09), - url: 'https://wger.de/media/gallery/170335/d2b9c9e0-d541-41ae-8786-a2ab459e3538.jpg', + url: + 'https://wger.de/media/gallery/170335/d2b9c9e0-d541-41ae-8786-a2ab459e3538.jpg', description: "eggsaddjujuit'ddayhadIforcanview", ); diff --git a/test/gallery/gallery_screen_test.dart b/test/gallery/gallery_screen_test.dart index 0f796ab19..747d0afa8 100644 --- a/test/gallery/gallery_screen_test.dart +++ b/test/gallery/gallery_screen_test.dart @@ -53,14 +53,16 @@ void main() { ); } - testWidgets('Test the widgets on the gallery screen', (WidgetTester tester) async { + testWidgets('Test the widgets on the gallery screen', + (WidgetTester tester) async { await mockNetworkImagesFor(() => tester.pumpWidget(createScreen())); expect(find.byType(SliverMasonryGrid), findsOneWidget); expect(find.byType(GestureDetector, skipOffstage: false), findsNWidgets(4)); }); - testWidgets('Test opening the form for an existing image', (WidgetTester tester) async { + testWidgets('Test opening the form for an existing image', + (WidgetTester tester) async { await mockNetworkImagesFor(() => tester.pumpWidget(createScreen())); await tester.tap(find.byKey(const Key('image-1'))); @@ -68,7 +70,8 @@ void main() { // Detail dialog opens expect(find.byKey(const Key('image-1-detail')), findsOneWidget); - expect(find.byType(Image), findsNWidgets(5)); // four in the overview, one in the popup + expect(find.byType(Image), + findsNWidgets(5)); // four in the overview, one in the popup expect(find.text('A very cool image from the gym'), findsOneWidget); expect(find.byIcon(Icons.edit), findsOneWidget); expect(find.byIcon(Icons.delete), findsOneWidget); @@ -82,7 +85,8 @@ void main() { expect(find.byType(ElevatedButton), findsOneWidget); }); - testWidgets('Tests the localization of dates - EN', (WidgetTester tester) async { + testWidgets('Tests the localization of dates - EN', + (WidgetTester tester) async { await mockNetworkImagesFor(() => tester.pumpWidget(createScreen())); await tester.tap(find.byKey(const Key('image-1'))); await tester.pumpAndSettle(); @@ -90,8 +94,10 @@ void main() { expect(find.text('5/30/2021'), findsOneWidget); }); - testWidgets('Tests the localization of dates - DE', (WidgetTester tester) async { - await mockNetworkImagesFor(() => tester.pumpWidget(createScreen(locale: 'de'))); + testWidgets('Tests the localization of dates - DE', + (WidgetTester tester) async { + await mockNetworkImagesFor( + () => tester.pumpWidget(createScreen(locale: 'de'))); await tester.tap(find.byKey(const Key('image-1'))); await tester.pumpAndSettle(); diff --git a/test/gallery/gallery_screen_test.mocks.dart b/test/gallery/gallery_screen_test.mocks.dart index 546c056e0..c35445e6d 100644 --- a/test/gallery/gallery_screen_test.mocks.dart +++ b/test/gallery/gallery_screen_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/gallery/gallery_screen_test.dart. // Do not manually edit this file. @@ -21,49 +21,30 @@ import 'package:wger/providers/gallery.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [GalleryProvider]. @@ -82,114 +63,71 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { @override set images(List<_i5.Image>? _images) => super.noSuchMethod( - Invocation.setter( - #images, - _images, - ), + Invocation.setter(#images, _images), returnValueForMissingStub: null, ); @override _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_0( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) as _i2.AuthProvider); @override set auth(_i2.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i6.Future fetchAndSetGallery() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetGallery, - [], - ), + Invocation.method(#fetchAndSetGallery, []), returnValue: _i6.Future.value(), returnValueForMissingStub: _i6.Future.value(), ) as _i6.Future); @override - _i6.Future addImage( - _i5.Image? image, - _i7.XFile? imageFile, - ) => + _i6.Future addImage(_i5.Image? image, _i7.XFile? imageFile) => (super.noSuchMethod( - Invocation.method( - #addImage, - [ - image, - imageFile, - ], - ), + Invocation.method(#addImage, [image, imageFile]), returnValue: _i6.Future.value(), returnValueForMissingStub: _i6.Future.value(), ) as _i6.Future); @override - _i6.Future editImage( - _i5.Image? image, - _i7.XFile? imageFile, - ) => + _i6.Future editImage(_i5.Image? image, _i7.XFile? imageFile) => (super.noSuchMethod( - Invocation.method( - #editImage, - [ - image, - imageFile, - ], - ), + Invocation.method(#editImage, [image, imageFile]), returnValue: _i6.Future.value(), returnValueForMissingStub: _i6.Future.value(), ) as _i6.Future); @override _i6.Future deleteImage(_i5.Image? image) => (super.noSuchMethod( - Invocation.method( - #deleteImage, - [image], - ), + Invocation.method(#deleteImage, [image]), returnValue: _i6.Future.value(), returnValueForMissingStub: _i6.Future.value(), ) as _i6.Future); @@ -197,11 +135,9 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -216,60 +152,39 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i6.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i6.Future>.value( + {}, ), - returnValue: - _i6.Future>.value({}), ) as _i6.Future>); @override _i6.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i6.Future>.value([]), ) as _i6.Future>); @override - _i6.Future> post( - Map? data, - Uri? uri, - ) => + _i6.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i6.Future>.value( + {}, ), - returnValue: - _i6.Future>.value({}), ) as _i6.Future>); @override @@ -278,75 +193,45 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i6.Future>.value( + {}, ), - returnValue: - _i6.Future>.value({}), ) as _i6.Future>); @override - _i6.Future<_i3.Response> deleteRequest( - String? url, - int? id, - ) => + _i6.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i6.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i6.Future<_i3.Response>); @override void addListener(_i8.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i8.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/measurements/measurement_categories_screen_test.dart b/test/measurements/measurement_categories_screen_test.dart index 75d8ad181..9dd411087 100644 --- a/test/measurements/measurement_categories_screen_test.dart +++ b/test/measurements/measurement_categories_screen_test.dart @@ -38,12 +38,32 @@ void main() { mockMeasurementProvider = MockMeasurementProvider(); when(mockMeasurementProvider.categories).thenReturn([ MeasurementCategory(id: 1, name: 'body fat', unit: '%', entries: [ - MeasurementEntry(id: 1, category: 1, date: DateTime(2021, 9, 1), value: 10, notes: ''), - MeasurementEntry(id: 2, category: 1, date: DateTime(2021, 9, 5), value: 11, notes: ''), + MeasurementEntry( + id: 1, + category: 1, + date: DateTime(2021, 9, 1), + value: 10, + notes: ''), + MeasurementEntry( + id: 2, + category: 1, + date: DateTime(2021, 9, 5), + value: 11, + notes: ''), ]), MeasurementCategory(id: 2, name: 'biceps', unit: 'cm', entries: [ - MeasurementEntry(id: 3, category: 2, date: DateTime(2021, 9, 1), value: 30, notes: ''), - MeasurementEntry(id: 4, category: 2, date: DateTime(2021, 9, 5), value: 40, notes: ''), + MeasurementEntry( + id: 3, + category: 2, + date: DateTime(2021, 9, 1), + value: 30, + notes: ''), + MeasurementEntry( + id: 4, + category: 2, + date: DateTime(2021, 9, 5), + value: 40, + notes: ''), ]), ]); }); @@ -60,7 +80,8 @@ void main() { ); } - testWidgets('Test the widgets on the measurement category screen', (WidgetTester tester) async { + testWidgets('Test the widgets on the measurement category screen', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); await tester.pumpAndSettle(); diff --git a/test/measurements/measurement_categories_screen_test.mocks.dart b/test/measurements/measurement_categories_screen_test.mocks.dart index 79c881368..2a76cf444 100644 --- a/test/measurements/measurement_categories_screen_test.mocks.dart +++ b/test/measurements/measurement_categories_screen_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/measurements/measurement_categories_screen_test.dart. // Do not manually edit this file. @@ -20,6 +20,7 @@ import 'package:wger/providers/measurement.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -27,24 +28,14 @@ import 'package:wger/providers/measurement.dart' as _i4; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMeasurementCategory_1 extends _i1.SmartFake implements _i3.MeasurementCategory { - _FakeMeasurementCategory_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMeasurementCategory_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [MeasurementProvider]. @@ -72,61 +63,42 @@ class MockMeasurementProvider extends _i1.Mock ) as List<_i3.MeasurementCategory>); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i3.MeasurementCategory findCategoryById(int? id) => (super.noSuchMethod( - Invocation.method( - #findCategoryById, - [id], - ), + Invocation.method(#findCategoryById, [id]), returnValue: _FakeMeasurementCategory_1( this, - Invocation.method( - #findCategoryById, - [id], - ), + Invocation.method(#findCategoryById, [id]), ), ) as _i3.MeasurementCategory); @override _i5.Future fetchAndSetCategories() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetCategories, - [], - ), + Invocation.method(#fetchAndSetCategories, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future fetchAndSetCategoryEntries(int? id) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetCategoryEntries, - [id], - ), + Invocation.method(#fetchAndSetCategoryEntries, [id]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future fetchAndSetAllCategoriesAndEntries() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllCategoriesAndEntries, - [], - ), + Invocation.method(#fetchAndSetAllCategoriesAndEntries, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -134,66 +106,36 @@ class MockMeasurementProvider extends _i1.Mock @override _i5.Future addCategory(_i3.MeasurementCategory? category) => (super.noSuchMethod( - Invocation.method( - #addCategory, - [category], - ), + Invocation.method(#addCategory, [category]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future deleteCategory(int? id) => (super.noSuchMethod( - Invocation.method( - #deleteCategory, - [id], - ), + Invocation.method(#deleteCategory, [id]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future editCategory( - int? id, - String? newName, - String? newUnit, - ) => + _i5.Future editCategory(int? id, String? newName, String? newUnit) => (super.noSuchMethod( - Invocation.method( - #editCategory, - [ - id, - newName, - newUnit, - ], - ), + Invocation.method(#editCategory, [id, newName, newUnit]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future addEntry(_i6.MeasurementEntry? entry) => (super.noSuchMethod( - Invocation.method( - #addEntry, - [entry], - ), + Invocation.method(#addEntry, [entry]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future deleteEntry( - int? id, - int? categoryId, - ) => - (super.noSuchMethod( - Invocation.method( - #deleteEntry, - [ - id, - categoryId, - ], - ), + _i5.Future deleteEntry(int? id, int? categoryId) => (super.noSuchMethod( + Invocation.method(#deleteEntry, [id, categoryId]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -207,53 +149,38 @@ class MockMeasurementProvider extends _i1.Mock DateTime? newDate, ) => (super.noSuchMethod( - Invocation.method( - #editEntry, - [ - id, - categoryId, - newValue, - newNotes, - newDate, - ], - ), + Invocation.method(#editEntry, [ + id, + categoryId, + newValue, + newNotes, + newDate, + ]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override void addListener(_i7.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i7.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/measurements/measurement_category_test.dart b/test/measurements/measurement_category_test.dart index 21009d0e7..d65dae074 100644 --- a/test/measurements/measurement_category_test.dart +++ b/test/measurements/measurement_category_test.dart @@ -76,7 +76,8 @@ void main() { test('should copyWith objects of this class', () { // arrange - final MeasurementCategory tMeasurementCategoryCopied = MeasurementCategory( + final MeasurementCategory tMeasurementCategoryCopied = + MeasurementCategory( id: 1234, name: 'Coolness', unit: 'lp', @@ -107,9 +108,11 @@ void main() { expect(result, tMeasurementEntry); }); - test('should throw a NoSuchEntryException if no MeasurementEntry was found', () { + test('should throw a NoSuchEntryException if no MeasurementEntry was found', + () { // act & assert - expect(() => tMeasurementCategory.findEntryById(83), throwsA(isA())); + expect(() => tMeasurementCategory.findEntryById(83), + throwsA(isA())); }); }); } diff --git a/test/measurements/measurement_entries_screen_test.dart b/test/measurements/measurement_entries_screen_test.dart index fef0b2efe..8bd80299c 100644 --- a/test/measurements/measurement_entries_screen_test.dart +++ b/test/measurements/measurement_entries_screen_test.dart @@ -38,8 +38,18 @@ void main() { mockMeasurementProvider = MockMeasurementProvider(); when(mockMeasurementProvider.findCategoryById(any)).thenReturn( MeasurementCategory(id: 1, name: 'body fat', unit: '%', entries: [ - MeasurementEntry(id: 1, category: 1, date: DateTime(2021, 8, 1), value: 10.2, notes: ''), - MeasurementEntry(id: 1, category: 1, date: DateTime(2021, 8, 10), value: 18.1, notes: 'a'), + MeasurementEntry( + id: 1, + category: 1, + date: DateTime(2021, 8, 1), + value: 10.2, + notes: ''), + MeasurementEntry( + id: 1, + category: 1, + date: DateTime(2021, 8, 10), + value: 18.1, + notes: 'a'), ]), ); @@ -73,7 +83,8 @@ void main() { ); } - testWidgets('Test the widgets on the measurement entries screen', (WidgetTester tester) async { + testWidgets('Test the widgets on the measurement entries screen', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); @@ -85,7 +96,8 @@ void main() { expect(find.text('15.0 %'), findsNWidgets(1)); }); - testWidgets('Tests the localization of dates - EN', (WidgetTester tester) async { + testWidgets('Tests the localization of dates - EN', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); @@ -95,7 +107,8 @@ void main() { expect(find.text('8/10/2021'), findsWidgets); }); - testWidgets('Tests the localization of dates - DE', (WidgetTester tester) async { + testWidgets('Tests the localization of dates - DE', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen(locale: 'de')); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); diff --git a/test/measurements/measurement_provider_test.dart b/test/measurements/measurement_provider_test.dart index 90f60bc14..ed16afa37 100644 --- a/test/measurements/measurement_provider_test.dart +++ b/test/measurements/measurement_provider_test.dart @@ -48,13 +48,15 @@ void main() { measurementProvider = MeasurementProvider(mockWgerBaseProvider); when(mockWgerBaseProvider.makeUrl(any)).thenReturn(tCategoryUri); - when(mockWgerBaseProvider.makeUrl(any, id: anyNamed('id'))).thenReturn(tCategoryUri); - when(mockWgerBaseProvider.fetch(any)) - .thenAnswer((realInvocation) => Future.value(tMeasurementCategoriesMap)); + when(mockWgerBaseProvider.makeUrl(any, id: anyNamed('id'))) + .thenReturn(tCategoryUri); + when(mockWgerBaseProvider.fetch(any)).thenAnswer( + (realInvocation) => Future.value(tMeasurementCategoriesMap)); when(mockWgerBaseProvider.makeUrl(entryUrl, query: anyNamed('query'))) .thenReturn(tCategoryEntriesUri); - when(mockWgerBaseProvider.makeUrl(entryUrl, id: anyNamed('id'), query: anyNamed('query'))) + when(mockWgerBaseProvider.makeUrl(entryUrl, + id: anyNamed('id'), query: anyNamed('query'))) .thenReturn(tCategoryEntriesUri); when(mockWgerBaseProvider.fetch(tCategoryEntriesUri)) .thenAnswer((realInvocation) => Future.value(tMeasurementCategoryMap)); @@ -90,7 +92,8 @@ void main() { test('should throw a NoResultException if no category is found', () { // act & assert - expect(() => measurementProvider.findCategoryById(3), throwsA(isA())); + expect(() => measurementProvider.findCategoryById(3), + throwsA(isA())); }); }); @@ -130,7 +133,8 @@ void main() { await measurementProvider.fetchAndSetCategoryEntries(tCategoryId); // assert - verify(mockWgerBaseProvider.makeUrl(entryUrl, query: {'category': tCategoryId.toString()})); + verify(mockWgerBaseProvider + .makeUrl(entryUrl, query: {'category': tCategoryId.toString()})); }); test('should fetch categories entries for id', () async { @@ -176,16 +180,16 @@ void main() { MeasurementCategory(id: null, name: 'Strength', unit: 'kN'); final Map tMeasurementCategoryMap = jsonDecode(fixture('measurement/measurement_category.json')); - final Map tMeasurementCategoryMapWithoutId = - jsonDecode(fixture('measurement/measurement_category_without_id_to_json.json')); + final Map tMeasurementCategoryMapWithoutId = jsonDecode( + fixture('measurement/measurement_category_without_id_to_json.json')); final List tMeasurementCategoriesAdded = [ const MeasurementCategory(id: 2, name: 'Biceps', unit: 'cm'), const MeasurementCategory(id: 1, name: 'Strength', unit: 'kN'), const MeasurementCategory(id: 1, name: 'Strength', unit: 'kN'), ]; setUp(() { - when(mockWgerBaseProvider.post(any, any)) - .thenAnswer((realInvocation) => Future.value(tMeasurementCategoryMap)); + when(mockWgerBaseProvider.post(any, any)).thenAnswer( + (realInvocation) => Future.value(tMeasurementCategoryMap)); }); test("should post the MeasurementCategorie's Map", () async { @@ -193,7 +197,8 @@ void main() { await measurementProvider.addCategory(tMeasurementCategoryWithoutId); // assert - verify(mockWgerBaseProvider.post(tMeasurementCategoryMapWithoutId, tCategoryUri)); + verify(mockWgerBaseProvider.post( + tMeasurementCategoryMapWithoutId, tCategoryUri)); }); test( @@ -230,21 +235,25 @@ void main() { await measurementProvider.deleteCategory(tCategoryId); // assert - verify(mockWgerBaseProvider.deleteRequest('measurement-category', tCategoryId)); - expect(measurementProvider.categories, tMeasurementCategoriesOneDeleted); + verify(mockWgerBaseProvider.deleteRequest( + 'measurement-category', tCategoryId)); + expect( + measurementProvider.categories, tMeasurementCategoriesOneDeleted); }, ); test('should throw a NoSuchEntryException if no category is found', () { // act & assert - expect(() => measurementProvider.deleteCategory(83), throwsA(isA())); + expect(() => measurementProvider.deleteCategory(83), + throwsA(isA())); }); test( 'should re-add the "removed" MeasurementCategory and relay the exception on WgerHttpException', () { // arrange - when(mockWgerBaseProvider.deleteRequest(any, any)).thenThrow(WgerHttpException('{}')); + when(mockWgerBaseProvider.deleteRequest(any, any)) + .thenThrow(WgerHttpException('{}')); // act & assert expect( @@ -259,8 +268,8 @@ void main() { group('editCategory()', () { const String tCategoryEditedName = 'Triceps'; const String tCategoryEditedUnit = 'm'; - final Map tCategoryMapEditedToJson = - jsonDecode(fixture('measurement/measurement_category_edited_to_json.json')); + final Map tCategoryMapEditedToJson = jsonDecode( + fixture('measurement/measurement_category_edited_to_json.json')); final Map tCategoryMapEdited = jsonDecode(fixture('measurement/measurement_category_edited.json')); setUp(() async { @@ -268,7 +277,8 @@ void main() { .thenAnswer((realInvocation) => Future.value(tCategoryMapEdited)); await measurementProvider.fetchAndSetCategories(); }); - test('should add the new MeasurementCategory and remove the old one', () async { + test('should add the new MeasurementCategory and remove the old one', + () async { // arrange final List tMeasurementCategoriesEdited = [ const MeasurementCategory(id: 1, name: 'Triceps', unit: 'm'), @@ -276,7 +286,8 @@ void main() { ]; // act - await measurementProvider.editCategory(tCategoryId, tCategoryEditedName, tCategoryEditedUnit); + await measurementProvider.editCategory( + tCategoryId, tCategoryEditedName, tCategoryEditedUnit); // assert expect(measurementProvider.categories, tMeasurementCategoriesEdited); @@ -285,22 +296,26 @@ void main() { test("should throw a NoSuchEntryException if category doesn't exist", () { // act & assert expect( - () => measurementProvider.editCategory(83, tCategoryEditedName, tCategoryEditedUnit), + () => measurementProvider.editCategory( + 83, tCategoryEditedName, tCategoryEditedUnit), throwsA(isA()), ); }); test('should call api to patch the category', () async { // act - await measurementProvider.editCategory(tCategoryId, tCategoryEditedName, tCategoryEditedUnit); + await measurementProvider.editCategory( + tCategoryId, tCategoryEditedName, tCategoryEditedUnit); // assert - verify(mockWgerBaseProvider.patch(tCategoryMapEditedToJson, tCategoryUri)); + verify( + mockWgerBaseProvider.patch(tCategoryMapEditedToJson, tCategoryUri)); }); test('should keep categories list as is on WgerHttpException', () { // arrange - when(mockWgerBaseProvider.patch(any, any)).thenThrow(WgerHttpException('{}')); + when(mockWgerBaseProvider.patch(any, any)) + .thenThrow(WgerHttpException('{}')); // act & assert expect( @@ -379,7 +394,8 @@ void main() { await measurementProvider.addEntry(tMeasurementEntryWithoutId); // assert - verify(mockWgerBaseProvider.post(measurementEntryMapWithoutId, tCategoryEntriesUri)); + verify(mockWgerBaseProvider.post( + measurementEntryMapWithoutId, tCategoryEntriesUri)); }); test( @@ -405,10 +421,10 @@ void main() { value: 15.00, notes: '', ); - final Map measurementEntryMapWrongCategory = - jsonDecode(fixture('measurement/measurement_entry_wrong_category.json')); - when(mockWgerBaseProvider.post(any, any)) - .thenAnswer((realInvocation) => Future.value(measurementEntryMapWrongCategory)); + final Map measurementEntryMapWrongCategory = jsonDecode( + fixture('measurement/measurement_entry_wrong_category.json')); + when(mockWgerBaseProvider.post(any, any)).thenAnswer( + (realInvocation) => Future.value(measurementEntryMapWrongCategory)); // act & assert expect( @@ -441,7 +457,9 @@ void main() { .thenAnswer((realInvocation) => Future.value(Response('', 200))); }); - test("should remove a MeasurementEntry from the category's entries List for an id", () async { + test( + "should remove a MeasurementEntry from the category's entries List for an id", + () async { // act await measurementProvider.deleteEntry(tEntryId, tCategoryId); @@ -499,7 +517,8 @@ void main() { ]), const MeasurementCategory(id: 2, name: 'Biceps', unit: 'cm'), ]; - when(mockWgerBaseProvider.deleteRequest(any, any)).thenThrow(WgerHttpException('{}')); + when(mockWgerBaseProvider.deleteRequest(any, any)) + .thenThrow(WgerHttpException('{}')); // act & assert expect( @@ -521,7 +540,8 @@ void main() { const int tEntryId = 1; const num tEntryEditedValue = 23; final DateTime tEntryEditedDate = DateTime(2021, 07, 21); - const String tEntryEditedNote = 'I just wanted to edit this to see what happens'; + const String tEntryEditedNote = + 'I just wanted to edit this to see what happens'; final Map tEntryMapEdited = jsonDecode(fixture('measurement/measurement_entry_edited.json')); setUp(() async { @@ -530,7 +550,8 @@ void main() { await measurementProvider.fetchAndSetCategories(); await measurementProvider.fetchAndSetCategoryEntries(1); }); - test('should add the new MeasurementEntry and remove the old one', () async { + test('should add the new MeasurementEntry and remove the old one', + () async { // arrange final List tMeasurementCategoriesEdited = [ MeasurementCategory(id: 1, name: 'Strength', unit: 'kN', entries: [ diff --git a/test/measurements/measurement_provider_test.mocks.dart b/test/measurements/measurement_provider_test.mocks.dart index bb54e9ecc..451006cff 100644 --- a/test/measurements/measurement_provider_test.mocks.dart +++ b/test/measurements/measurement_provider_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/measurements/measurement_provider_test.dart. // Do not manually edit this file. @@ -18,49 +18,30 @@ import 'package:wger/providers/base_provider.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -74,47 +55,33 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { @override _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_0( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) as _i2.AuthProvider); @override set auth(_i2.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -129,60 +96,39 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i5.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override _i5.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i5.Future>.value([]), ) as _i5.Future>); @override - _i5.Future> post( - Map? data, - Uri? uri, - ) => + _i5.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override @@ -191,39 +137,21 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override - _i5.Future<_i3.Response> deleteRequest( - String? url, - int? id, - ) => + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i5.Future<_i3.Response>); } diff --git a/test/nutrition/nutrition_provider_test.dart b/test/nutrition/nutrition_provider_test.dart index 2b8fb842a..93fb08c69 100644 --- a/test/nutrition/nutrition_provider_test.dart +++ b/test/nutrition/nutrition_provider_test.dart @@ -77,9 +77,12 @@ void main() { host: 'localhost', path: 'api/v2/$ingredientInfoUrl', ); - when(mockWgerBaseProvider.makeUrl(planInfoUrl, id: anyNamed('id'))).thenReturn(planInfoUri); - when(mockWgerBaseProvider.makeUrl(planUrl, id: anyNamed('id'))).thenReturn(planUri); - when(mockWgerBaseProvider.makeUrl(diaryUrl, query: anyNamed('query'))).thenReturn(diaryUri); + when(mockWgerBaseProvider.makeUrl(planInfoUrl, id: anyNamed('id'))) + .thenReturn(planInfoUri); + when(mockWgerBaseProvider.makeUrl(planUrl, id: anyNamed('id'))) + .thenReturn(planUri); + when(mockWgerBaseProvider.makeUrl(diaryUrl, query: anyNamed('query'))) + .thenReturn(diaryUri); when(mockWgerBaseProvider.makeUrl(ingredientInfoUrl, id: anyNamed('id'))) .thenReturn(ingredientUri); when(mockWgerBaseProvider.fetch(planInfoUri)).thenAnswer( @@ -111,7 +114,8 @@ void main() { }); group('Ingredient cache DB', () { - test('that if there is already valid data in the DB, the API is not hit', () async { + test('that if there is already valid data in the DB, the API is not hit', + () async { // Arrange nutritionProvider.ingredients = []; await database.into(database.ingredients).insert( @@ -132,7 +136,8 @@ void main() { verifyNever(mockWgerBaseProvider.fetchPaginated(any)); }); - test('fetching an ingredient not present in the DB, the API is hit', () async { + test('fetching an ingredient not present in the DB, the API is hit', + () async { // Arrange nutritionProvider.ingredients = []; await database.into(database.ingredients).insert( @@ -149,7 +154,8 @@ void main() { // Assert expect(nutritionProvider.ingredients.length, 1); expect(nutritionProvider.ingredients.first.id, 10065); - expect(nutritionProvider.ingredients.first.name, "'Old Times' Orange Fine Cut Marmalade"); + expect(nutritionProvider.ingredients.first.name, + "'Old Times' Orange Fine Cut Marmalade"); verify(mockWgerBaseProvider.fetch(any)); }); }); diff --git a/test/nutrition/nutritional_diary_test.dart b/test/nutrition/nutritional_diary_test.dart index 515b20d47..1920450af 100644 --- a/test/nutrition/nutritional_diary_test.dart +++ b/test/nutrition/nutritional_diary_test.dart @@ -32,13 +32,15 @@ void main() { supportedLocales: AppLocalizations.supportedLocales, home: SingleChildScrollView( child: Card( - child: NutritionalDiaryDetailWidget(getNutritionalPlan(), DateTime(2021, 6, 1)), + child: NutritionalDiaryDetailWidget( + getNutritionalPlan(), DateTime(2021, 6, 1)), ), ), ); } - testWidgets('Test the detail view for the nutritional plan', (WidgetTester tester) async { + testWidgets('Test the detail view for the nutritional plan', + (WidgetTester tester) async { await tester.pumpWidget(getWidget()); expect(find.byType(FlNutritionalPlanPieChartWidget), findsOneWidget); @@ -49,11 +51,14 @@ void main() { expect(find.text('18 g'), findsOneWidget, reason: 'find grams of carbs'); expect(find.text('4 g'), findsOneWidget, reason: 'find grams of sugar'); expect(find.text('29 g'), findsOneWidget, reason: 'find grams of fat'); - expect(find.text('14 g'), findsOneWidget, reason: 'find grams of saturated fat'); + expect(find.text('14 g'), findsOneWidget, + reason: 'find grams of saturated fat'); expect(find.text('50 g'), findsOneWidget, reason: 'find grams of fiber'); - expect(find.text('100 g Water'), findsOneWidget, reason: 'Name of ingredient'); - expect(find.text('75 g Burger soup'), findsOneWidget, reason: 'Name of ingredient'); + expect(find.text('100 g Water'), findsOneWidget, + reason: 'Name of ingredient'); + expect(find.text('75 g Burger soup'), findsOneWidget, + reason: 'Name of ingredient'); expect(find.byIcon(Icons.delete_outline), findsNWidgets(2)); }); } diff --git a/test/nutrition/nutritional_meal_form_test.dart b/test/nutrition/nutritional_meal_form_test.dart index fdb781f64..f07c9bca5 100644 --- a/test/nutrition/nutritional_meal_form_test.dart +++ b/test/nutrition/nutritional_meal_form_test.dart @@ -62,7 +62,8 @@ void main() { navigatorKey: key, home: Scaffold(body: MealForm(1, meal)), routes: { - NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(), + NutritionalPlanScreen.routeName: (ctx) => + const NutritionalPlanScreen(), }, ), ); @@ -102,7 +103,8 @@ void main() { verifyNever(mockNutrition.addMeal(any, any)); }); - testWidgets('Test creating a new nutritional plan', (WidgetTester tester) async { + testWidgets('Test creating a new nutritional plan', + (WidgetTester tester) async { // DateTime.now() is difficult to mock as it pull directly from the platform // currently being run. The clock pacakge (https://pub.dev/packages/clock) // addresses this issue, using clock.now() allows us to set a fixed value as the diff --git a/test/nutrition/nutritional_meal_form_test.mocks.dart b/test/nutrition/nutritional_meal_form_test.mocks.dart index 3df6d7b22..515d9a210 100644 --- a/test/nutrition/nutritional_meal_form_test.mocks.dart +++ b/test/nutrition/nutritional_meal_form_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/nutrition/nutritional_meal_form_test.dart. // Do not manually edit this file. @@ -24,6 +24,7 @@ import 'package:wger/providers/nutrition.dart' as _i8; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -31,65 +32,35 @@ import 'package:wger/providers/nutrition.dart' as _i8; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIngredientDatabase_1 extends _i1.SmartFake implements _i3.IngredientDatabase { - _FakeIngredientDatabase_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIngredientDatabase_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeNutritionalPlan_2 extends _i1.SmartFake implements _i4.NutritionalPlan { - _FakeNutritionalPlan_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeNutritionalPlan_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMeal_3 extends _i1.SmartFake implements _i5.Meal { - _FakeMeal_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMeal_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMealItem_4 extends _i1.SmartFake implements _i6.MealItem { - _FakeMealItem_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMealItem_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIngredient_5 extends _i1.SmartFake implements _i7.Ingredient { - _FakeIngredient_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIngredient_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [NutritionPlansProvider]. @@ -121,10 +92,7 @@ class MockNutritionPlansProvider extends _i1.Mock @override set database(_i3.IngredientDatabase? _database) => super.noSuchMethod( - Invocation.setter( - #database, - _database, - ), + Invocation.setter(#database, _database), returnValueForMissingStub: null, ); @@ -136,10 +104,7 @@ class MockNutritionPlansProvider extends _i1.Mock @override set ingredients(List<_i7.Ingredient>? _ingredients) => super.noSuchMethod( - Invocation.setter( - #ingredients, - _ingredients, - ), + Invocation.setter(#ingredients, _ingredients), returnValueForMissingStub: null, ); @@ -150,57 +115,39 @@ class MockNutritionPlansProvider extends _i1.Mock ) as List<_i4.NutritionalPlan>); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i4.NutritionalPlan findById(int? id) => (super.noSuchMethod( - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), returnValue: _FakeNutritionalPlan_2( this, - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), ), ) as _i4.NutritionalPlan); @override - _i5.Meal? findMealById(int? id) => (super.noSuchMethod(Invocation.method( - #findMealById, - [id], - )) as _i5.Meal?); + _i5.Meal? findMealById(int? id) => + (super.noSuchMethod(Invocation.method(#findMealById, [id])) as _i5.Meal?); @override _i9.Future fetchAndSetAllPlansSparse() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansSparse, - [], - ), + Invocation.method(#fetchAndSetAllPlansSparse, []), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override _i9.Future fetchAndSetAllPlansFull() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansFull, - [], - ), + Invocation.method(#fetchAndSetAllPlansFull, []), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -208,120 +155,73 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanSparse, - [planId], - ), - returnValue: - _i9.Future<_i4.NutritionalPlan>.value(_FakeNutritionalPlan_2( - this, - Invocation.method( - #fetchAndSetPlanSparse, - [planId], + Invocation.method(#fetchAndSetPlanSparse, [planId]), + returnValue: _i9.Future<_i4.NutritionalPlan>.value( + _FakeNutritionalPlan_2( + this, + Invocation.method(#fetchAndSetPlanSparse, [planId]), ), - )), + ), ) as _i9.Future<_i4.NutritionalPlan>); @override _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanFull(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanFull, - [planId], - ), - returnValue: - _i9.Future<_i4.NutritionalPlan>.value(_FakeNutritionalPlan_2( - this, - Invocation.method( - #fetchAndSetPlanFull, - [planId], + Invocation.method(#fetchAndSetPlanFull, [planId]), + returnValue: _i9.Future<_i4.NutritionalPlan>.value( + _FakeNutritionalPlan_2( + this, + Invocation.method(#fetchAndSetPlanFull, [planId]), ), - )), + ), ) as _i9.Future<_i4.NutritionalPlan>); @override _i9.Future<_i4.NutritionalPlan> addPlan(_i4.NutritionalPlan? planData) => (super.noSuchMethod( - Invocation.method( - #addPlan, - [planData], - ), - returnValue: - _i9.Future<_i4.NutritionalPlan>.value(_FakeNutritionalPlan_2( - this, - Invocation.method( - #addPlan, - [planData], + Invocation.method(#addPlan, [planData]), + returnValue: _i9.Future<_i4.NutritionalPlan>.value( + _FakeNutritionalPlan_2( + this, + Invocation.method(#addPlan, [planData]), ), - )), + ), ) as _i9.Future<_i4.NutritionalPlan>); @override _i9.Future editPlan(_i4.NutritionalPlan? plan) => (super.noSuchMethod( - Invocation.method( - #editPlan, - [plan], - ), + Invocation.method(#editPlan, [plan]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override _i9.Future deletePlan(int? id) => (super.noSuchMethod( - Invocation.method( - #deletePlan, - [id], - ), + Invocation.method(#deletePlan, [id]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override - _i9.Future<_i5.Meal> addMeal( - _i5.Meal? meal, - int? planId, - ) => + _i9.Future<_i5.Meal> addMeal(_i5.Meal? meal, int? planId) => (super.noSuchMethod( - Invocation.method( - #addMeal, - [ - meal, - planId, - ], + Invocation.method(#addMeal, [meal, planId]), + returnValue: _i9.Future<_i5.Meal>.value( + _FakeMeal_3(this, Invocation.method(#addMeal, [meal, planId])), ), - returnValue: _i9.Future<_i5.Meal>.value(_FakeMeal_3( - this, - Invocation.method( - #addMeal, - [ - meal, - planId, - ], - ), - )), ) as _i9.Future<_i5.Meal>); @override _i9.Future<_i5.Meal> editMeal(_i5.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #editMeal, - [meal], + Invocation.method(#editMeal, [meal]), + returnValue: _i9.Future<_i5.Meal>.value( + _FakeMeal_3(this, Invocation.method(#editMeal, [meal])), ), - returnValue: _i9.Future<_i5.Meal>.value(_FakeMeal_3( - this, - Invocation.method( - #editMeal, - [meal], - ), - )), ) as _i9.Future<_i5.Meal>); @override _i9.Future deleteMeal(_i5.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #deleteMeal, - [meal], - ), + Invocation.method(#deleteMeal, [meal]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -332,42 +232,26 @@ class MockNutritionPlansProvider extends _i1.Mock _i5.Meal? meal, ) => (super.noSuchMethod( - Invocation.method( - #addMealItem, - [ - mealItem, - meal, - ], - ), - returnValue: _i9.Future<_i6.MealItem>.value(_FakeMealItem_4( - this, - Invocation.method( - #addMealItem, - [ - mealItem, - meal, - ], + Invocation.method(#addMealItem, [mealItem, meal]), + returnValue: _i9.Future<_i6.MealItem>.value( + _FakeMealItem_4( + this, + Invocation.method(#addMealItem, [mealItem, meal]), ), - )), + ), ) as _i9.Future<_i6.MealItem>); @override _i9.Future deleteMealItem(_i6.MealItem? mealItem) => (super.noSuchMethod( - Invocation.method( - #deleteMealItem, - [mealItem], - ), + Invocation.method(#deleteMealItem, [mealItem]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override _i9.Future clearIngredientCache() => (super.noSuchMethod( - Invocation.method( - #clearIngredientCache, - [], - ), + Invocation.method(#clearIngredientCache, []), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -383,22 +267,21 @@ class MockNutritionPlansProvider extends _i1.Mock [ingredientId], {#database: database}, ), - returnValue: _i9.Future<_i7.Ingredient>.value(_FakeIngredient_5( - this, - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, + returnValue: _i9.Future<_i7.Ingredient>.value( + _FakeIngredient_5( + this, + Invocation.method( + #fetchIngredient, + [ingredientId], + {#database: database}, + ), ), - )), + ), ) as _i9.Future<_i7.Ingredient>); @override _i9.Future fetchIngredientsFromCache() => (super.noSuchMethod( - Invocation.method( - #fetchIngredientsFromCache, - [], - ), + Invocation.method(#fetchIngredientsFromCache, []), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -406,38 +289,30 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i9.Future> searchIngredient( String? name, { - String? languageCode = r'en', + String? languageCode = 'en', bool? searchEnglish = false, }) => (super.noSuchMethod( Invocation.method( #searchIngredient, [name], - { - #languageCode: languageCode, - #searchEnglish: searchEnglish, - }, + {#languageCode: languageCode, #searchEnglish: searchEnglish}, ), returnValue: _i9.Future>.value( - <_i10.IngredientApiSearchEntry>[]), + <_i10.IngredientApiSearchEntry>[], + ), ) as _i9.Future>); @override _i9.Future<_i7.Ingredient?> searchIngredientWithCode(String? code) => (super.noSuchMethod( - Invocation.method( - #searchIngredientWithCode, - [code], - ), + Invocation.method(#searchIngredientWithCode, [code]), returnValue: _i9.Future<_i7.Ingredient?>.value(), ) as _i9.Future<_i7.Ingredient?>); @override _i9.Future logMealToDiary(_i5.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #logMealToDiary, - [meal], - ), + Invocation.method(#logMealToDiary, [meal]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -449,31 +324,18 @@ class MockNutritionPlansProvider extends _i1.Mock DateTime? dateTime, ]) => (super.noSuchMethod( - Invocation.method( - #logIngredientToDiary, - [ - mealItem, - planId, - dateTime, - ], - ), + Invocation.method(#logIngredientToDiary, [ + mealItem, + planId, + dateTime, + ]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override - _i9.Future deleteLog( - int? logId, - int? planId, - ) => - (super.noSuchMethod( - Invocation.method( - #deleteLog, - [ - logId, - planId, - ], - ), + _i9.Future deleteLog(int? logId, int? planId) => (super.noSuchMethod( + Invocation.method(#deleteLog, [logId, planId]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -481,47 +343,32 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i9.Future fetchAndSetLogs(_i4.NutritionalPlan? plan) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetLogs, - [plan], - ), + Invocation.method(#fetchAndSetLogs, [plan]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override void addListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/nutrition/nutritional_meal_item_form_test.dart b/test/nutrition/nutritional_meal_item_form_test.dart index e37435e98..9d5b3d1a3 100644 --- a/test/nutrition/nutritional_meal_item_form_test.dart +++ b/test/nutrition/nutritional_meal_item_form_test.dart @@ -49,20 +49,26 @@ void main() { var plan1 = NutritionalPlan.empty(); var meal1 = Meal(); - final Uri tUriRightCode = Uri.parse('https://localhost/api/v2/ingredientinfo/?code=123'); - final Uri tUriEmptyCode = Uri.parse('https://localhost/api/v2/ingredientinfo/?code="%20"'); - final Uri tUriBadCode = Uri.parse('https://localhost/api/v2/ingredientinfo/?code=222'); + final Uri tUriRightCode = + Uri.parse('https://localhost/api/v2/ingredientinfo/?code=123'); + final Uri tUriEmptyCode = + Uri.parse('https://localhost/api/v2/ingredientinfo/?code="%20"'); + final Uri tUriBadCode = + Uri.parse('https://localhost/api/v2/ingredientinfo/?code=222'); when(client.get(tUriRightCode, headers: anyNamed('headers'))).thenAnswer( - (_) => Future.value(http.Response(fixture('nutrition/ingredientinfo_right_code.json'), 200)), + (_) => Future.value(http.Response( + fixture('nutrition/ingredientinfo_right_code.json'), 200)), ); when(client.get(tUriEmptyCode, headers: anyNamed('headers'))).thenAnswer( - (_) => Future.value(http.Response(fixture('nutrition/ingredientinfo_wrong_code.json'), 200)), + (_) => Future.value(http.Response( + fixture('nutrition/ingredientinfo_wrong_code.json'), 200)), ); when(client.get(tUriBadCode, headers: anyNamed('headers'))).thenAnswer( - (_) => Future.value(http.Response(fixture('nutrition/ingredientinfo_wrong_code.json'), 200)), + (_) => Future.value(http.Response( + fixture('nutrition/ingredientinfo_wrong_code.json'), 200)), ); setUp(() { @@ -71,24 +77,30 @@ void main() { final MealItem mealItem = MealItem(ingredientId: ingredient.id, amount: 2); mockNutrition = MockNutritionPlansProvider(); - when(mockNutrition.searchIngredientWithCode('123')).thenAnswer((_) => Future.value(ingredient)); - when(mockNutrition.searchIngredientWithCode('')).thenAnswer((_) => Future.value(null)); - when(mockNutrition.searchIngredientWithCode('222')).thenAnswer((_) => Future.value(null)); + when(mockNutrition.searchIngredientWithCode('123')) + .thenAnswer((_) => Future.value(ingredient)); + when(mockNutrition.searchIngredientWithCode('')) + .thenAnswer((_) => Future.value(null)); + when(mockNutrition.searchIngredientWithCode('222')) + .thenAnswer((_) => Future.value(null)); when(mockNutrition.searchIngredient( any, languageCode: anyNamed('languageCode'), searchEnglish: anyNamed('searchEnglish'), )).thenAnswer( (_) => Future.value( - IngredientApiSearch.fromJson(json.decode(fixture('nutrition/ingredient_suggestions'))) + IngredientApiSearch.fromJson( + json.decode(fixture('nutrition/ingredient_suggestions'))) .suggestions, ), ); - when(mockNutrition.addMealItem(any, meal1)).thenAnswer((_) => Future.value(mealItem)); + when(mockNutrition.addMealItem(any, meal1)) + .thenAnswer((_) => Future.value(mealItem)); }); - Widget createMealItemFormScreen(Meal meal, String code, bool test, {locale = 'en'}) { + Widget createMealItemFormScreen(Meal meal, String code, bool test, + {locale = 'en'}) { final key = GlobalKey(); return ChangeNotifierProvider( @@ -105,17 +117,20 @@ void main() { ), ), routes: { - NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(), + NutritionalPlanScreen.routeName: (ctx) => + const NutritionalPlanScreen(), }, ), ); } - testWidgets('Test the widgets on the meal item form', (WidgetTester tester) async { + testWidgets('Test the widgets on the meal item form', + (WidgetTester tester) async { await tester.pumpWidget(createMealItemFormScreen(meal1, '', true)); await tester.pumpAndSettle(); - expect(find.byType(TypeAheadField), findsOneWidget); + expect( + find.byType(TypeAheadField), findsOneWidget); expect(find.byType(TextFormField), findsWidgets); expect(find.byKey(const Key('scan-button')), findsOneWidget); expect(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), findsOneWidget); @@ -131,8 +146,11 @@ void main() { await tester.tap(find.byKey(const Key('scan-button'))); await tester.pumpAndSettle(); - expect(find.byKey(const Key('ingredient-scan-result-dialog')), findsOneWidget); - expect(find.byKey(const Key('ingredient-scan-result-dialog-confirm-button')), findsNothing); + expect(find.byKey(const Key('ingredient-scan-result-dialog')), + findsOneWidget); + expect( + find.byKey(const Key('ingredient-scan-result-dialog-confirm-button')), + findsNothing); }); testWidgets('with correct code', (WidgetTester tester) async { @@ -141,8 +159,11 @@ void main() { await tester.tap(find.byKey(const Key('scan-button'))); await tester.pumpAndSettle(); - expect(find.byKey(const Key('ingredient-scan-result-dialog')), findsOneWidget); - expect(find.byKey(const Key('ingredient-scan-result-dialog-confirm-button')), findsOneWidget); + expect(find.byKey(const Key('ingredient-scan-result-dialog')), + findsOneWidget); + expect( + find.byKey(const Key('ingredient-scan-result-dialog-confirm-button')), + findsOneWidget); }); testWidgets('with incorrect code', (WidgetTester tester) async { @@ -151,8 +172,11 @@ void main() { await tester.tap(find.byKey(const Key('scan-button'))); await tester.pumpAndSettle(); - expect(find.byKey(const Key('ingredient-scan-result-dialog')), findsOneWidget); - expect(find.byKey(const Key('ingredient-scan-result-dialog-confirm-button')), findsNothing); + expect(find.byKey(const Key('ingredient-scan-result-dialog')), + findsOneWidget); + expect( + find.byKey(const Key('ingredient-scan-result-dialog-confirm-button')), + findsNothing); }); }); @@ -217,14 +241,17 @@ void main() { testWidgets('confirm found ingredient dialog', (WidgetTester tester) async { await tester.pumpWidget(createMealItemFormScreen(meal1, '123', true)); - final IngredientFormState formState = tester.state(find.byType(IngredientForm)); + final IngredientFormState formState = + tester.state(find.byType(IngredientForm)); await tester.tap(find.byKey(const Key('scan-button'))); await tester.pumpAndSettle(); - expect(find.byKey(const Key('ingredient-scan-result-dialog')), findsOneWidget); + expect(find.byKey(const Key('ingredient-scan-result-dialog')), + findsOneWidget); - await tester.tap(find.byKey(const Key('ingredient-scan-result-dialog-confirm-button'))); + await tester.tap(find + .byKey(const Key('ingredient-scan-result-dialog-confirm-button'))); await tester.pumpAndSettle(); expect(formState.ingredientIdController.text, '1'); @@ -236,12 +263,15 @@ void main() { await tester.tap(find.byKey(const Key('scan-button'))); await tester.pumpAndSettle(); - expect(find.byKey(const Key('ingredient-scan-result-dialog')), findsOneWidget); + expect(find.byKey(const Key('ingredient-scan-result-dialog')), + findsOneWidget); - await tester.tap(find.byKey(const Key('ingredient-scan-result-dialog-close-button'))); + await tester.tap( + find.byKey(const Key('ingredient-scan-result-dialog-close-button'))); await tester.pumpAndSettle(); - expect(find.byKey(const Key('ingredient-scan-result-dialog')), findsNothing); + expect( + find.byKey(const Key('ingredient-scan-result-dialog')), findsNothing); }); }); @@ -265,9 +295,11 @@ void main() { await tester.tap(find.byKey(const Key('scan-button'))); await tester.pumpAndSettle(); - expect(find.byKey(const Key('ingredient-scan-result-dialog')), findsOneWidget); + expect(find.byKey(const Key('ingredient-scan-result-dialog')), + findsOneWidget); - await tester.tap(find.byKey(const Key('ingredient-scan-result-dialog-confirm-button'))); + await tester.tap(find + .byKey(const Key('ingredient-scan-result-dialog-confirm-button'))); await tester.pumpAndSettle(); await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); @@ -277,15 +309,18 @@ void main() { }); //TODO: isn't this test just a duplicate of the above one? can be removed? - testWidgets('save ingredient with incorrect weight input type', (WidgetTester tester) async { + testWidgets('save ingredient with incorrect weight input type', + (WidgetTester tester) async { await tester.pumpWidget(createMealItemFormScreen(meal1, '123', true)); await tester.tap(find.byKey(const Key('scan-button'))); await tester.pumpAndSettle(); - expect(find.byKey(const Key('ingredient-scan-result-dialog')), findsOneWidget); + expect(find.byKey(const Key('ingredient-scan-result-dialog')), + findsOneWidget); - await tester.tap(find.byKey(const Key('ingredient-scan-result-dialog-confirm-button'))); + await tester.tap(find + .byKey(const Key('ingredient-scan-result-dialog-confirm-button'))); await tester.pumpAndSettle(); await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); @@ -299,14 +334,17 @@ void main() { (WidgetTester tester) async { await tester.pumpWidget(createMealItemFormScreen(meal1, '123', true)); - final IngredientFormState formState = tester.state(find.byType(IngredientForm)); + final IngredientFormState formState = + tester.state(find.byType(IngredientForm)); await tester.tap(find.byKey(const Key('scan-button'))); await tester.pumpAndSettle(); - expect(find.byKey(const Key('ingredient-scan-result-dialog')), findsOneWidget); + expect(find.byKey(const Key('ingredient-scan-result-dialog')), + findsOneWidget); - await tester.tap(find.byKey(const Key('ingredient-scan-result-dialog-confirm-button'))); + await tester.tap(find + .byKey(const Key('ingredient-scan-result-dialog-confirm-button'))); await tester.pumpAndSettle(); expect(formState.ingredientIdController.text, '1'); @@ -315,11 +353,13 @@ void main() { // once ID and weight are set, it'll fetchIngredient and show macros preview and ingredient image when(mockNutrition.fetchIngredient(1)).thenAnswer((_) => Future.value( - Ingredient.fromJson(jsonDecode(fixture('nutrition/ingredientinfo_59887.json'))), + Ingredient.fromJson( + jsonDecode(fixture('nutrition/ingredientinfo_59887.json'))), )); await mockNetworkImagesFor(() => tester.pumpAndSettle()); - expect(find.byKey(const Key('ingredient-scan-result-dialog')), findsNothing); + expect(find.byKey(const Key('ingredient-scan-result-dialog')), + findsNothing); await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); await tester.pumpAndSettle(); diff --git a/test/nutrition/nutritional_plan_form_test.dart b/test/nutrition/nutritional_plan_form_test.dart index e366ef51f..fdc77835e 100644 --- a/test/nutrition/nutritional_plan_form_test.dart +++ b/test/nutrition/nutritional_plan_form_test.dart @@ -58,15 +58,17 @@ void main() { localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, navigatorKey: key, - home: Scaffold(body: PlanForm(plan)), + home: Scaffold(body: PlanForm(plan: plan)), routes: { - NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(), + NutritionalPlanScreen.routeName: (ctx) => + const NutritionalPlanScreen(), }, ), ); } - testWidgets('Test the widgets on the nutritional plan form', (WidgetTester tester) async { + testWidgets('Test the widgets on the nutritional plan form', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen(plan1)); await tester.pumpAndSettle(); @@ -75,7 +77,8 @@ void main() { expect(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME)), findsOneWidget); }); - testWidgets('Test editing an existing nutritional plan', (WidgetTester tester) async { + testWidgets('Test editing an existing nutritional plan', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen(plan1)); await tester.pumpAndSettle(); @@ -84,7 +87,8 @@ void main() { findsOneWidget, reason: 'Description of existing nutritional plan is filled in', ); - await tester.enterText(find.byKey(const Key('field-description')), 'New description'); + await tester.enterText( + find.byKey(const Key('field-description')), 'New description'); await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); // Correct method was called @@ -105,12 +109,15 @@ void main() { //); }); - testWidgets('Test creating a new nutritional plan', (WidgetTester tester) async { + testWidgets('Test creating a new nutritional plan', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen(plan2)); await tester.pumpAndSettle(); - expect(find.text(''), findsOneWidget, reason: 'New nutritional plan has no description'); - await tester.enterText(find.byKey(const Key('field-description')), 'New cool plan'); + expect(find.text(''), findsOneWidget, + reason: 'New nutritional plan has no description'); + await tester.enterText( + find.byKey(const Key('field-description')), 'New cool plan'); await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); // Correct method was called @@ -119,6 +126,7 @@ void main() { // Detail page await tester.pumpAndSettle(); - expect(find.text('New cool plan'), findsOneWidget, reason: 'Nutritional plan detail page'); + expect(find.text('New cool plan'), findsOneWidget, + reason: 'Nutritional plan detail page'); }); } diff --git a/test/nutrition/nutritional_plan_form_test.mocks.dart b/test/nutrition/nutritional_plan_form_test.mocks.dart index 3b48c5305..c65f0ab14 100644 --- a/test/nutrition/nutritional_plan_form_test.mocks.dart +++ b/test/nutrition/nutritional_plan_form_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/nutrition/nutritional_plan_form_test.dart. // Do not manually edit this file. @@ -24,6 +24,7 @@ import 'package:wger/providers/nutrition.dart' as _i8; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -31,65 +32,35 @@ import 'package:wger/providers/nutrition.dart' as _i8; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIngredientDatabase_1 extends _i1.SmartFake implements _i3.IngredientDatabase { - _FakeIngredientDatabase_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIngredientDatabase_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeNutritionalPlan_2 extends _i1.SmartFake implements _i4.NutritionalPlan { - _FakeNutritionalPlan_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeNutritionalPlan_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMeal_3 extends _i1.SmartFake implements _i5.Meal { - _FakeMeal_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMeal_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMealItem_4 extends _i1.SmartFake implements _i6.MealItem { - _FakeMealItem_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMealItem_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIngredient_5 extends _i1.SmartFake implements _i7.Ingredient { - _FakeIngredient_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIngredient_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [NutritionPlansProvider]. @@ -121,10 +92,7 @@ class MockNutritionPlansProvider extends _i1.Mock @override set database(_i3.IngredientDatabase? _database) => super.noSuchMethod( - Invocation.setter( - #database, - _database, - ), + Invocation.setter(#database, _database), returnValueForMissingStub: null, ); @@ -136,10 +104,7 @@ class MockNutritionPlansProvider extends _i1.Mock @override set ingredients(List<_i7.Ingredient>? _ingredients) => super.noSuchMethod( - Invocation.setter( - #ingredients, - _ingredients, - ), + Invocation.setter(#ingredients, _ingredients), returnValueForMissingStub: null, ); @@ -150,57 +115,39 @@ class MockNutritionPlansProvider extends _i1.Mock ) as List<_i4.NutritionalPlan>); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i4.NutritionalPlan findById(int? id) => (super.noSuchMethod( - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), returnValue: _FakeNutritionalPlan_2( this, - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), ), ) as _i4.NutritionalPlan); @override - _i5.Meal? findMealById(int? id) => (super.noSuchMethod(Invocation.method( - #findMealById, - [id], - )) as _i5.Meal?); + _i5.Meal? findMealById(int? id) => + (super.noSuchMethod(Invocation.method(#findMealById, [id])) as _i5.Meal?); @override _i9.Future fetchAndSetAllPlansSparse() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansSparse, - [], - ), + Invocation.method(#fetchAndSetAllPlansSparse, []), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override _i9.Future fetchAndSetAllPlansFull() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansFull, - [], - ), + Invocation.method(#fetchAndSetAllPlansFull, []), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -208,120 +155,73 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanSparse, - [planId], - ), - returnValue: - _i9.Future<_i4.NutritionalPlan>.value(_FakeNutritionalPlan_2( - this, - Invocation.method( - #fetchAndSetPlanSparse, - [planId], + Invocation.method(#fetchAndSetPlanSparse, [planId]), + returnValue: _i9.Future<_i4.NutritionalPlan>.value( + _FakeNutritionalPlan_2( + this, + Invocation.method(#fetchAndSetPlanSparse, [planId]), ), - )), + ), ) as _i9.Future<_i4.NutritionalPlan>); @override _i9.Future<_i4.NutritionalPlan> fetchAndSetPlanFull(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanFull, - [planId], - ), - returnValue: - _i9.Future<_i4.NutritionalPlan>.value(_FakeNutritionalPlan_2( - this, - Invocation.method( - #fetchAndSetPlanFull, - [planId], + Invocation.method(#fetchAndSetPlanFull, [planId]), + returnValue: _i9.Future<_i4.NutritionalPlan>.value( + _FakeNutritionalPlan_2( + this, + Invocation.method(#fetchAndSetPlanFull, [planId]), ), - )), + ), ) as _i9.Future<_i4.NutritionalPlan>); @override _i9.Future<_i4.NutritionalPlan> addPlan(_i4.NutritionalPlan? planData) => (super.noSuchMethod( - Invocation.method( - #addPlan, - [planData], - ), - returnValue: - _i9.Future<_i4.NutritionalPlan>.value(_FakeNutritionalPlan_2( - this, - Invocation.method( - #addPlan, - [planData], + Invocation.method(#addPlan, [planData]), + returnValue: _i9.Future<_i4.NutritionalPlan>.value( + _FakeNutritionalPlan_2( + this, + Invocation.method(#addPlan, [planData]), ), - )), + ), ) as _i9.Future<_i4.NutritionalPlan>); @override _i9.Future editPlan(_i4.NutritionalPlan? plan) => (super.noSuchMethod( - Invocation.method( - #editPlan, - [plan], - ), + Invocation.method(#editPlan, [plan]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override _i9.Future deletePlan(int? id) => (super.noSuchMethod( - Invocation.method( - #deletePlan, - [id], - ), + Invocation.method(#deletePlan, [id]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override - _i9.Future<_i5.Meal> addMeal( - _i5.Meal? meal, - int? planId, - ) => + _i9.Future<_i5.Meal> addMeal(_i5.Meal? meal, int? planId) => (super.noSuchMethod( - Invocation.method( - #addMeal, - [ - meal, - planId, - ], + Invocation.method(#addMeal, [meal, planId]), + returnValue: _i9.Future<_i5.Meal>.value( + _FakeMeal_3(this, Invocation.method(#addMeal, [meal, planId])), ), - returnValue: _i9.Future<_i5.Meal>.value(_FakeMeal_3( - this, - Invocation.method( - #addMeal, - [ - meal, - planId, - ], - ), - )), ) as _i9.Future<_i5.Meal>); @override _i9.Future<_i5.Meal> editMeal(_i5.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #editMeal, - [meal], + Invocation.method(#editMeal, [meal]), + returnValue: _i9.Future<_i5.Meal>.value( + _FakeMeal_3(this, Invocation.method(#editMeal, [meal])), ), - returnValue: _i9.Future<_i5.Meal>.value(_FakeMeal_3( - this, - Invocation.method( - #editMeal, - [meal], - ), - )), ) as _i9.Future<_i5.Meal>); @override _i9.Future deleteMeal(_i5.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #deleteMeal, - [meal], - ), + Invocation.method(#deleteMeal, [meal]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -332,42 +232,26 @@ class MockNutritionPlansProvider extends _i1.Mock _i5.Meal? meal, ) => (super.noSuchMethod( - Invocation.method( - #addMealItem, - [ - mealItem, - meal, - ], - ), - returnValue: _i9.Future<_i6.MealItem>.value(_FakeMealItem_4( - this, - Invocation.method( - #addMealItem, - [ - mealItem, - meal, - ], + Invocation.method(#addMealItem, [mealItem, meal]), + returnValue: _i9.Future<_i6.MealItem>.value( + _FakeMealItem_4( + this, + Invocation.method(#addMealItem, [mealItem, meal]), ), - )), + ), ) as _i9.Future<_i6.MealItem>); @override _i9.Future deleteMealItem(_i6.MealItem? mealItem) => (super.noSuchMethod( - Invocation.method( - #deleteMealItem, - [mealItem], - ), + Invocation.method(#deleteMealItem, [mealItem]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override _i9.Future clearIngredientCache() => (super.noSuchMethod( - Invocation.method( - #clearIngredientCache, - [], - ), + Invocation.method(#clearIngredientCache, []), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -383,22 +267,21 @@ class MockNutritionPlansProvider extends _i1.Mock [ingredientId], {#database: database}, ), - returnValue: _i9.Future<_i7.Ingredient>.value(_FakeIngredient_5( - this, - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, + returnValue: _i9.Future<_i7.Ingredient>.value( + _FakeIngredient_5( + this, + Invocation.method( + #fetchIngredient, + [ingredientId], + {#database: database}, + ), ), - )), + ), ) as _i9.Future<_i7.Ingredient>); @override _i9.Future fetchIngredientsFromCache() => (super.noSuchMethod( - Invocation.method( - #fetchIngredientsFromCache, - [], - ), + Invocation.method(#fetchIngredientsFromCache, []), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -406,38 +289,30 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i9.Future> searchIngredient( String? name, { - String? languageCode = r'en', + String? languageCode = 'en', bool? searchEnglish = false, }) => (super.noSuchMethod( Invocation.method( #searchIngredient, [name], - { - #languageCode: languageCode, - #searchEnglish: searchEnglish, - }, + {#languageCode: languageCode, #searchEnglish: searchEnglish}, ), returnValue: _i9.Future>.value( - <_i10.IngredientApiSearchEntry>[]), + <_i10.IngredientApiSearchEntry>[], + ), ) as _i9.Future>); @override _i9.Future<_i7.Ingredient?> searchIngredientWithCode(String? code) => (super.noSuchMethod( - Invocation.method( - #searchIngredientWithCode, - [code], - ), + Invocation.method(#searchIngredientWithCode, [code]), returnValue: _i9.Future<_i7.Ingredient?>.value(), ) as _i9.Future<_i7.Ingredient?>); @override _i9.Future logMealToDiary(_i5.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #logMealToDiary, - [meal], - ), + Invocation.method(#logMealToDiary, [meal]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -449,31 +324,18 @@ class MockNutritionPlansProvider extends _i1.Mock DateTime? dateTime, ]) => (super.noSuchMethod( - Invocation.method( - #logIngredientToDiary, - [ - mealItem, - planId, - dateTime, - ], - ), + Invocation.method(#logIngredientToDiary, [ + mealItem, + planId, + dateTime, + ]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override - _i9.Future deleteLog( - int? logId, - int? planId, - ) => - (super.noSuchMethod( - Invocation.method( - #deleteLog, - [ - logId, - planId, - ], - ), + _i9.Future deleteLog(int? logId, int? planId) => (super.noSuchMethod( + Invocation.method(#deleteLog, [logId, planId]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @@ -481,47 +343,32 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i9.Future fetchAndSetLogs(_i4.NutritionalPlan? plan) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetLogs, - [plan], - ), + Invocation.method(#fetchAndSetLogs, [plan]), returnValue: _i9.Future.value(), returnValueForMissingStub: _i9.Future.value(), ) as _i9.Future); @override void addListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/nutrition/nutritional_plan_model_test.dart b/test/nutrition/nutritional_plan_model_test.dart index ac35a1628..e63226599 100644 --- a/test/nutrition/nutritional_plan_model_test.dart +++ b/test/nutrition/nutritional_plan_model_test.dart @@ -46,7 +46,8 @@ void main() { ), ); }); - test('Test NutritionalPlan.nutritionalValues based on 3 macros and energy', () { + test('Test NutritionalPlan.nutritionalValues based on 3 macros and energy', + () { expect( NutritionalPlan( description: '3 macros and energy defined', @@ -64,7 +65,8 @@ void main() { ), ); }); - test('Test NutritionalPlan.nutritionalValues based on 2 macros and energy', () { + test('Test NutritionalPlan.nutritionalValues based on 2 macros and energy', + () { expect( NutritionalPlan( description: '2 macros and energy defined', @@ -101,12 +103,14 @@ void main() { test('Test the nutritionalValues method for meals', () { final meal = plan.meals.first; - final values = NutritionalValues.values(518.75, 5.75, 17.5, 3.5, 29.0, 13.75, 49.5, 0.5); + final values = NutritionalValues.values( + 518.75, 5.75, 17.5, 3.5, 29.0, 13.75, 49.5, 0.5); expect(meal.plannedNutritionalValues, values); }); test('Test that the getter returns all meal items for a plan', () { - expect(plan.dedupMealItems, plan.meals[0].mealItems + plan.meals[1].mealItems); + expect(plan.dedupMealItems, + plan.meals[0].mealItems + plan.meals[1].mealItems); }); }); } diff --git a/test/nutrition/nutritional_plan_screen_test.dart b/test/nutrition/nutritional_plan_screen_test.dart index e22f93083..163b9a089 100644 --- a/test/nutrition/nutritional_plan_screen_test.dart +++ b/test/nutrition/nutritional_plan_screen_test.dart @@ -102,16 +102,19 @@ void main() { // Default view shows plan description, info button, and no ingredients expect(find.text('Less fat, more protein'), findsOneWidget); - expect(find.byIcon(Icons.info_outline), findsNWidgets(3)); // 2 meals, 1 "other logs" + expect(find.byIcon(Icons.info_outline), + findsNWidgets(3)); // 2 meals, 1 "other logs" expect(find.byIcon(Icons.info), findsNothing); expect(find.text('100g Water'), findsNothing); expect(find.text('75g Burger soup'), findsNothing); // tap the first info button changes it and reveals ingredients for the first meal var infoOutlineButtons = find.byIcon(Icons.info_outline); - await tester.tap(infoOutlineButtons.first); // 2nd button shows up also, but is off-screen + await tester.tap(infoOutlineButtons + .first); // 2nd button shows up also, but is off-screen await tester.pumpAndSettle(); - await screenMatchesGolden(tester, 'nutritional_plan_2_one_meal_with_ingredients'); + await screenMatchesGolden( + tester, 'nutritional_plan_2_one_meal_with_ingredients'); // Ingredients show up now expect(find.text('100g Water'), findsOneWidget); @@ -130,7 +133,8 @@ void main() { await tester.tap(infoOutlineButtons.first); await tester.pumpAndSettle(); - await screenMatchesGolden(tester, 'nutritional_plan_3_both_meals_with_ingredients'); + await screenMatchesGolden( + tester, 'nutritional_plan_3_both_meals_with_ingredients'); expect(find.byIcon(Icons.info_outline), findsOneWidget); expect(find.byIcon(Icons.info), findsNWidgets(2)); @@ -141,7 +145,8 @@ void main() { }, ); - testWidgets('Tests the localization of times - EN', (WidgetTester tester) async { + testWidgets('Tests the localization of times - EN', + (WidgetTester tester) async { await tester.pumpWidget(createNutritionalPlan()); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); @@ -149,7 +154,8 @@ void main() { expect(find.textContaining('5:00 PM'), findsOneWidget); }); - testWidgets('Tests the localization of times - DE', (WidgetTester tester) async { + testWidgets('Tests the localization of times - DE', + (WidgetTester tester) async { await tester.pumpWidget(createNutritionalPlan(locale: 'de')); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); diff --git a/test/nutrition/nutritional_plan_screen_test.mocks.dart b/test/nutrition/nutritional_plan_screen_test.mocks.dart index 57c8ebeb0..1acb3e9f1 100644 --- a/test/nutrition/nutritional_plan_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plan_screen_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/nutrition/nutritional_plan_screen_test.dart. // Do not manually edit this file. @@ -23,60 +23,36 @@ import 'package:wger/providers/base_provider.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeStreamedResponse_4 extends _i1.SmartFake implements _i3.StreamedResponse { - _FakeStreamedResponse_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeStreamedResponse_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -90,47 +66,33 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { @override _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_0( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) as _i2.AuthProvider); @override set auth(_i2.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -145,60 +107,39 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i5.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override _i5.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i5.Future>.value([]), ) as _i5.Future>); @override - _i5.Future> post( - Map? data, - Uri? uri, - ) => + _i5.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override @@ -207,40 +148,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override - _i5.Future<_i3.Response> deleteRequest( - String? url, - int? id, - ) => + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i5.Future<_i3.Response>); } @@ -254,38 +177,26 @@ class MockAuthProvider extends _i1.Mock implements _i2.AuthProvider { @override set token(String? _token) => super.noSuchMethod( - Invocation.setter( - #token, - _token, - ), + Invocation.setter(#token, _token), returnValueForMissingStub: null, ); @override set serverUrl(String? _serverUrl) => super.noSuchMethod( - Invocation.setter( - #serverUrl, - _serverUrl, - ), + Invocation.setter(#serverUrl, _serverUrl), returnValueForMissingStub: null, ); @override set serverVersion(String? _serverVersion) => super.noSuchMethod( - Invocation.setter( - #serverVersion, - _serverVersion, - ), + Invocation.setter(#serverVersion, _serverVersion), returnValueForMissingStub: null, ); @override set applicationVersion(_i6.PackageInfo? _applicationVersion) => super.noSuchMethod( - Invocation.setter( - #applicationVersion, - _applicationVersion, - ), + Invocation.setter(#applicationVersion, _applicationVersion), returnValueForMissingStub: null, ); @@ -297,84 +208,60 @@ class MockAuthProvider extends _i1.Mock implements _i2.AuthProvider { @override set metadata(Map? _metadata) => super.noSuchMethod( - Invocation.setter( - #metadata, - _metadata, - ), + Invocation.setter(#metadata, _metadata), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override - bool get dataInit => (super.noSuchMethod( - Invocation.getter(#dataInit), - returnValue: false, - ) as bool); + bool get dataInit => + (super.noSuchMethod(Invocation.getter(#dataInit), returnValue: false) + as bool); @override set dataInit(bool? _dataInit) => super.noSuchMethod( - Invocation.setter( - #dataInit, - _dataInit, - ), + Invocation.setter(#dataInit, _dataInit), returnValueForMissingStub: null, ); @override - bool get isAuth => (super.noSuchMethod( - Invocation.getter(#isAuth), - returnValue: false, - ) as bool); + bool get isAuth => + (super.noSuchMethod(Invocation.getter(#isAuth), returnValue: false) + as bool); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override _i5.Future setServerVersion() => (super.noSuchMethod( - Invocation.method( - #setServerVersion, - [], - ), + Invocation.method(#setServerVersion, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setApplicationVersion() => (super.noSuchMethod( - Invocation.method( - #setApplicationVersion, - [], - ), + Invocation.method(#setApplicationVersion, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future initVersions(String? serverUrl) => (super.noSuchMethod( - Invocation.method( - #initVersions, - [serverUrl], - ), + Invocation.method(#initVersions, [serverUrl]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -385,13 +272,7 @@ class MockAuthProvider extends _i1.Mock implements _i2.AuthProvider { Map? metadata, ]) => (super.noSuchMethod( - Invocation.method( - #applicationUpdateRequired, - [ - version, - metadata, - ], - ), + Invocation.method(#applicationUpdateRequired, [version, metadata]), returnValue: _i5.Future.value(false), ) as _i5.Future); @@ -401,22 +282,19 @@ class MockAuthProvider extends _i1.Mock implements _i2.AuthProvider { required String? password, required String? email, required String? serverUrl, - String? locale = r'en', + String? locale = 'en', }) => (super.noSuchMethod( - Invocation.method( - #register, - [], - { - #username: username, - #password: password, - #email: email, - #serverUrl: serverUrl, - #locale: locale, - }, - ), + Invocation.method(#register, [], { + #username: username, + #password: password, + #email: email, + #serverUrl: serverUrl, + #locale: locale, + }), returnValue: _i5.Future>.value( - {}), + {}, + ), ) as _i5.Future>); @override @@ -426,101 +304,66 @@ class MockAuthProvider extends _i1.Mock implements _i2.AuthProvider { String? serverUrl, ) => (super.noSuchMethod( - Invocation.method( - #login, - [ - username, - password, - serverUrl, - ], - ), + Invocation.method(#login, [username, password, serverUrl]), returnValue: _i5.Future>.value( - {}), + {}, + ), ) as _i5.Future>); @override _i5.Future getServerUrlFromPrefs() => (super.noSuchMethod( - Invocation.method( - #getServerUrlFromPrefs, - [], - ), - returnValue: _i5.Future.value(_i7.dummyValue( - this, - Invocation.method( - #getServerUrlFromPrefs, - [], + Invocation.method(#getServerUrlFromPrefs, []), + returnValue: _i5.Future.value( + _i7.dummyValue( + this, + Invocation.method(#getServerUrlFromPrefs, []), ), - )), + ), ) as _i5.Future); @override _i5.Future tryAutoLogin() => (super.noSuchMethod( - Invocation.method( - #tryAutoLogin, - [], - ), + Invocation.method(#tryAutoLogin, []), returnValue: _i5.Future.value(false), ) as _i5.Future); @override _i5.Future logout({bool? shouldNotify = true}) => (super.noSuchMethod( - Invocation.method( - #logout, - [], - {#shouldNotify: shouldNotify}, - ), + Invocation.method(#logout, [], {#shouldNotify: shouldNotify}), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override String getAppNameHeader() => (super.noSuchMethod( - Invocation.method( - #getAppNameHeader, - [], - ), + Invocation.method(#getAppNameHeader, []), returnValue: _i7.dummyValue( this, - Invocation.method( - #getAppNameHeader, - [], - ), + Invocation.method(#getAppNameHeader, []), ), ) as String); @override void addListener(_i8.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i8.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } @@ -534,45 +377,27 @@ class MockClient extends _i1.Mock implements _i3.Client { } @override - _i5.Future<_i3.Response> head( - Uri? url, { - Map? headers, - }) => + _i5.Future<_i3.Response> head(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #head, - [url], - {#headers: headers}, - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #head, - [url], - {#headers: headers}, + Invocation.method(#head, [url], {#headers: headers}), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#head, [url], {#headers: headers}), ), - )), + ), ) as _i5.Future<_i3.Response>); @override - _i5.Future<_i3.Response> get( - Uri? url, { - Map? headers, - }) => + _i5.Future<_i3.Response> get(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #get, - [url], - {#headers: headers}, - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #get, - [url], - {#headers: headers}, + Invocation.method(#get, [url], {#headers: headers}), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#get, [url], {#headers: headers}), ), - )), + ), ) as _i5.Future<_i3.Response>); @override @@ -586,24 +411,18 @@ class MockClient extends _i1.Mock implements _i3.Client { Invocation.method( #post, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #post, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i5.Future<_i3.Response>); @override @@ -617,24 +436,18 @@ class MockClient extends _i1.Mock implements _i3.Client { Invocation.method( #put, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #put, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i5.Future<_i3.Response>); @override @@ -648,24 +461,18 @@ class MockClient extends _i1.Mock implements _i3.Client { Invocation.method( #patch, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #patch, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i5.Future<_i3.Response>); @override @@ -679,45 +486,30 @@ class MockClient extends _i1.Mock implements _i3.Client { Invocation.method( #delete, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #delete, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i5.Future<_i3.Response>); @override - _i5.Future read( - Uri? url, { - Map? headers, - }) => + _i5.Future read(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #read, - [url], - {#headers: headers}, - ), - returnValue: _i5.Future.value(_i7.dummyValue( - this, - Invocation.method( - #read, - [url], - {#headers: headers}, + Invocation.method(#read, [url], {#headers: headers}), + returnValue: _i5.Future.value( + _i7.dummyValue( + this, + Invocation.method(#read, [url], {#headers: headers}), ), - )), + ), ) as _i5.Future); @override @@ -726,37 +518,25 @@ class MockClient extends _i1.Mock implements _i3.Client { Map? headers, }) => (super.noSuchMethod( - Invocation.method( - #readBytes, - [url], - {#headers: headers}, - ), + Invocation.method(#readBytes, [url], {#headers: headers}), returnValue: _i5.Future<_i10.Uint8List>.value(_i10.Uint8List(0)), ) as _i5.Future<_i10.Uint8List>); @override _i5.Future<_i3.StreamedResponse> send(_i3.BaseRequest? request) => (super.noSuchMethod( - Invocation.method( - #send, - [request], - ), - returnValue: - _i5.Future<_i3.StreamedResponse>.value(_FakeStreamedResponse_4( - this, - Invocation.method( - #send, - [request], + Invocation.method(#send, [request]), + returnValue: _i5.Future<_i3.StreamedResponse>.value( + _FakeStreamedResponse_4( + this, + Invocation.method(#send, [request]), ), - )), + ), ) as _i5.Future<_i3.StreamedResponse>); @override void close() => super.noSuchMethod( - Invocation.method( - #close, - [], - ), + Invocation.method(#close, []), returnValueForMissingStub: null, ); } diff --git a/test/nutrition/nutritional_plans_screen_test.dart b/test/nutrition/nutritional_plans_screen_test.dart index 5a60b2503..556d8a58a 100644 --- a/test/nutrition/nutritional_plans_screen_test.dart +++ b/test/nutrition/nutritional_plans_screen_test.dart @@ -89,7 +89,8 @@ void main() { ); } - testWidgets('Test the widgets on the nutritional plans screen', (WidgetTester tester) async { + testWidgets('Test the widgets on the nutritional plans screen', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); //debugDumpApp(); @@ -98,7 +99,8 @@ void main() { expect(find.byType(ListTile), findsNWidgets(2)); }); - testWidgets('Test deleting an item using the Delete button', (WidgetTester tester) async { + testWidgets('Test deleting an item using the Delete button', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); await tester.tap(find.byIcon(Icons.delete).first); @@ -114,7 +116,8 @@ void main() { expect(find.byType(ListTile), findsOneWidget); }); - testWidgets('Test the form on the nutritional plan screen', (WidgetTester tester) async { + testWidgets('Test the form on the nutritional plan screen', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); expect(find.byType(PlanForm), findsNothing); @@ -123,14 +126,16 @@ void main() { expect(find.byType(PlanForm), findsOneWidget); }); - testWidgets('Tests the localization of dates - EN', (WidgetTester tester) async { + testWidgets('Tests the localization of dates - EN', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); expect(find.text('1/1/2021'), findsOneWidget); expect(find.text('1/10/2021'), findsOneWidget); }); - testWidgets('Tests the localization of dates - DE', (WidgetTester tester) async { + testWidgets('Tests the localization of dates - DE', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen(locale: 'de')); expect(find.text('1.1.2021'), findsOneWidget); diff --git a/test/nutrition/nutritional_plans_screen_test.mocks.dart b/test/nutrition/nutritional_plans_screen_test.mocks.dart index aa705cfbd..c05c9be46 100644 --- a/test/nutrition/nutritional_plans_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plans_screen_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/nutrition/nutritional_plans_screen_test.dart. // Do not manually edit this file. @@ -23,60 +23,36 @@ import 'package:wger/providers/base_provider.dart' as _i8; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeClient_0 extends _i1.SmartFake implements _i2.Client { - _FakeClient_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAuthProvider_1 extends _i1.SmartFake implements _i3.AuthProvider { - _FakeAuthProvider_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i2.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeStreamedResponse_4 extends _i1.SmartFake implements _i2.StreamedResponse { - _FakeStreamedResponse_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeStreamedResponse_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [AuthProvider]. @@ -89,38 +65,26 @@ class MockAuthProvider extends _i1.Mock implements _i3.AuthProvider { @override set token(String? _token) => super.noSuchMethod( - Invocation.setter( - #token, - _token, - ), + Invocation.setter(#token, _token), returnValueForMissingStub: null, ); @override set serverUrl(String? _serverUrl) => super.noSuchMethod( - Invocation.setter( - #serverUrl, - _serverUrl, - ), + Invocation.setter(#serverUrl, _serverUrl), returnValueForMissingStub: null, ); @override set serverVersion(String? _serverVersion) => super.noSuchMethod( - Invocation.setter( - #serverVersion, - _serverVersion, - ), + Invocation.setter(#serverVersion, _serverVersion), returnValueForMissingStub: null, ); @override set applicationVersion(_i4.PackageInfo? _applicationVersion) => super.noSuchMethod( - Invocation.setter( - #applicationVersion, - _applicationVersion, - ), + Invocation.setter(#applicationVersion, _applicationVersion), returnValueForMissingStub: null, ); @@ -132,84 +96,60 @@ class MockAuthProvider extends _i1.Mock implements _i3.AuthProvider { @override set metadata(Map? _metadata) => super.noSuchMethod( - Invocation.setter( - #metadata, - _metadata, - ), + Invocation.setter(#metadata, _metadata), returnValueForMissingStub: null, ); @override _i2.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_0( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_0(this, Invocation.getter(#client)), ) as _i2.Client); @override set client(_i2.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override - bool get dataInit => (super.noSuchMethod( - Invocation.getter(#dataInit), - returnValue: false, - ) as bool); + bool get dataInit => + (super.noSuchMethod(Invocation.getter(#dataInit), returnValue: false) + as bool); @override set dataInit(bool? _dataInit) => super.noSuchMethod( - Invocation.setter( - #dataInit, - _dataInit, - ), + Invocation.setter(#dataInit, _dataInit), returnValueForMissingStub: null, ); @override - bool get isAuth => (super.noSuchMethod( - Invocation.getter(#isAuth), - returnValue: false, - ) as bool); + bool get isAuth => + (super.noSuchMethod(Invocation.getter(#isAuth), returnValue: false) + as bool); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override _i5.Future setServerVersion() => (super.noSuchMethod( - Invocation.method( - #setServerVersion, - [], - ), + Invocation.method(#setServerVersion, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setApplicationVersion() => (super.noSuchMethod( - Invocation.method( - #setApplicationVersion, - [], - ), + Invocation.method(#setApplicationVersion, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future initVersions(String? serverUrl) => (super.noSuchMethod( - Invocation.method( - #initVersions, - [serverUrl], - ), + Invocation.method(#initVersions, [serverUrl]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -220,13 +160,7 @@ class MockAuthProvider extends _i1.Mock implements _i3.AuthProvider { Map? metadata, ]) => (super.noSuchMethod( - Invocation.method( - #applicationUpdateRequired, - [ - version, - metadata, - ], - ), + Invocation.method(#applicationUpdateRequired, [version, metadata]), returnValue: _i5.Future.value(false), ) as _i5.Future); @@ -236,22 +170,19 @@ class MockAuthProvider extends _i1.Mock implements _i3.AuthProvider { required String? password, required String? email, required String? serverUrl, - String? locale = r'en', + String? locale = 'en', }) => (super.noSuchMethod( - Invocation.method( - #register, - [], - { - #username: username, - #password: password, - #email: email, - #serverUrl: serverUrl, - #locale: locale, - }, - ), + Invocation.method(#register, [], { + #username: username, + #password: password, + #email: email, + #serverUrl: serverUrl, + #locale: locale, + }), returnValue: _i5.Future>.value( - {}), + {}, + ), ) as _i5.Future>); @override @@ -261,101 +192,66 @@ class MockAuthProvider extends _i1.Mock implements _i3.AuthProvider { String? serverUrl, ) => (super.noSuchMethod( - Invocation.method( - #login, - [ - username, - password, - serverUrl, - ], - ), + Invocation.method(#login, [username, password, serverUrl]), returnValue: _i5.Future>.value( - {}), + {}, + ), ) as _i5.Future>); @override _i5.Future getServerUrlFromPrefs() => (super.noSuchMethod( - Invocation.method( - #getServerUrlFromPrefs, - [], - ), - returnValue: _i5.Future.value(_i6.dummyValue( - this, - Invocation.method( - #getServerUrlFromPrefs, - [], + Invocation.method(#getServerUrlFromPrefs, []), + returnValue: _i5.Future.value( + _i6.dummyValue( + this, + Invocation.method(#getServerUrlFromPrefs, []), ), - )), + ), ) as _i5.Future); @override _i5.Future tryAutoLogin() => (super.noSuchMethod( - Invocation.method( - #tryAutoLogin, - [], - ), + Invocation.method(#tryAutoLogin, []), returnValue: _i5.Future.value(false), ) as _i5.Future); @override _i5.Future logout({bool? shouldNotify = true}) => (super.noSuchMethod( - Invocation.method( - #logout, - [], - {#shouldNotify: shouldNotify}, - ), + Invocation.method(#logout, [], {#shouldNotify: shouldNotify}), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override String getAppNameHeader() => (super.noSuchMethod( - Invocation.method( - #getAppNameHeader, - [], - ), + Invocation.method(#getAppNameHeader, []), returnValue: _i6.dummyValue( this, - Invocation.method( - #getAppNameHeader, - [], - ), + Invocation.method(#getAppNameHeader, []), ), ) as String); @override void addListener(_i7.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i7.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } @@ -371,47 +267,33 @@ class MockWgerBaseProvider extends _i1.Mock implements _i8.WgerBaseProvider { @override _i3.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_1( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_1(this, Invocation.getter(#auth)), ) as _i3.AuthProvider); @override set auth(_i3.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i2.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_0( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_0(this, Invocation.getter(#client)), ) as _i2.Client); @override set client(_i2.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -426,60 +308,39 @@ class MockWgerBaseProvider extends _i1.Mock implements _i8.WgerBaseProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i5.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override _i5.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i5.Future>.value([]), ) as _i5.Future>); @override - _i5.Future> post( - Map? data, - Uri? uri, - ) => + _i5.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override @@ -488,40 +349,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i8.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override - _i5.Future<_i2.Response> deleteRequest( - String? url, - int? id, - ) => + _i5.Future<_i2.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i5.Future<_i2.Response>); } @@ -534,45 +377,27 @@ class MockClient extends _i1.Mock implements _i2.Client { } @override - _i5.Future<_i2.Response> head( - Uri? url, { - Map? headers, - }) => + _i5.Future<_i2.Response> head(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #head, - [url], - {#headers: headers}, - ), - returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #head, - [url], - {#headers: headers}, + Invocation.method(#head, [url], {#headers: headers}), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#head, [url], {#headers: headers}), ), - )), + ), ) as _i5.Future<_i2.Response>); @override - _i5.Future<_i2.Response> get( - Uri? url, { - Map? headers, - }) => + _i5.Future<_i2.Response> get(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #get, - [url], - {#headers: headers}, - ), - returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #get, - [url], - {#headers: headers}, + Invocation.method(#get, [url], {#headers: headers}), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#get, [url], {#headers: headers}), ), - )), + ), ) as _i5.Future<_i2.Response>); @override @@ -586,24 +411,18 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #post, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #post, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_3( + this, + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i5.Future<_i2.Response>); @override @@ -617,24 +436,18 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #put, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #put, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_3( + this, + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i5.Future<_i2.Response>); @override @@ -648,24 +461,18 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #patch, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #patch, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_3( + this, + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i5.Future<_i2.Response>); @override @@ -679,45 +486,30 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #delete, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, - ), - returnValue: _i5.Future<_i2.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #delete, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i5.Future<_i2.Response>.value( + _FakeResponse_3( + this, + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i5.Future<_i2.Response>); @override - _i5.Future read( - Uri? url, { - Map? headers, - }) => + _i5.Future read(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #read, - [url], - {#headers: headers}, - ), - returnValue: _i5.Future.value(_i6.dummyValue( - this, - Invocation.method( - #read, - [url], - {#headers: headers}, + Invocation.method(#read, [url], {#headers: headers}), + returnValue: _i5.Future.value( + _i6.dummyValue( + this, + Invocation.method(#read, [url], {#headers: headers}), ), - )), + ), ) as _i5.Future); @override @@ -726,37 +518,25 @@ class MockClient extends _i1.Mock implements _i2.Client { Map? headers, }) => (super.noSuchMethod( - Invocation.method( - #readBytes, - [url], - {#headers: headers}, - ), + Invocation.method(#readBytes, [url], {#headers: headers}), returnValue: _i5.Future<_i10.Uint8List>.value(_i10.Uint8List(0)), ) as _i5.Future<_i10.Uint8List>); @override _i5.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( - Invocation.method( - #send, - [request], - ), - returnValue: - _i5.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_4( - this, - Invocation.method( - #send, - [request], + Invocation.method(#send, [request]), + returnValue: _i5.Future<_i2.StreamedResponse>.value( + _FakeStreamedResponse_4( + this, + Invocation.method(#send, [request]), ), - )), + ), ) as _i5.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( - Invocation.method( - #close, - [], - ), + Invocation.method(#close, []), returnValueForMissingStub: null, ); } diff --git a/test/nutrition/nutritional_values_class_test.dart b/test/nutrition/nutritional_values_class_test.dart index 495f95fe0..f6ea1a681 100644 --- a/test/nutrition/nutritional_values_class_test.dart +++ b/test/nutrition/nutritional_values_class_test.dart @@ -27,9 +27,12 @@ void main() { group('Test the NutritionalValues class', () { setUp(() { - values1 = NutritionalValues.values(4000, 30.5, 340.5, 11.7, 41.0, 31.75, 21.3, 33.3); - values2 = NutritionalValues.values(4000, 30.5, 340.5, 11.7, 41.0, 31.75, 21.3, 33.3); - values3 = NutritionalValues.values(5000, 30.5, 340.5, 11.7, 41.0, 31.75, 21.3, 33.3); + values1 = NutritionalValues.values( + 4000, 30.5, 340.5, 11.7, 41.0, 31.75, 21.3, 33.3); + values2 = NutritionalValues.values( + 4000, 30.5, 340.5, 11.7, 41.0, 31.75, 21.3, 33.3); + values3 = NutritionalValues.values( + 5000, 30.5, 340.5, 11.7, 41.0, 31.75, 21.3, 33.3); values4 = NutritionalValues.values(1000, 10, 100, 1, 10.0, 10, 10, 10); }); @@ -40,13 +43,15 @@ void main() { test('Test the plus operator', () { final values5 = values1 + values4; - final result = NutritionalValues.values(5000, 40.5, 440.5, 12.7, 51.0, 41.75, 31.3, 43.3); + final result = NutritionalValues.values( + 5000, 40.5, 440.5, 12.7, 51.0, 41.75, 31.3, 43.3); expect(values5, result); }); test('Test the add method', () { values1.add(values4); - final result = NutritionalValues.values(5000, 40.5, 440.5, 12.7, 51.0, 41.75, 31.3, 43.3); + final result = NutritionalValues.values( + 5000, 40.5, 440.5, 12.7, 51.0, 41.75, 31.3, 43.3); expect(values1, result); }); }); diff --git a/test/other/base_provider_test.dart b/test/other/base_provider_test.dart index 3f3376d2d..91db6de56 100644 --- a/test/other/base_provider_test.dart +++ b/test/other/base_provider_test.dart @@ -50,16 +50,20 @@ void main() { provider.makeUrl('endpoint', query: {'a': '2', 'b': 'c'}), ); expect( - Uri.https('localhost', '/api/v2/endpoint/log_data/', {'a': '2', 'b': 'c'}), - provider.makeUrl('endpoint', objectMethod: 'log_data', query: {'a': '2', 'b': 'c'}), + Uri.https( + 'localhost', '/api/v2/endpoint/log_data/', {'a': '2', 'b': 'c'}), + provider.makeUrl('endpoint', + objectMethod: 'log_data', query: {'a': '2', 'b': 'c'}), ); expect( Uri.https('localhost', '/api/v2/endpoint/42/', {'a': '2', 'b': 'c'}), provider.makeUrl('endpoint', id: 42, query: {'a': '2', 'b': 'c'}), ); expect( - Uri.https('localhost', '/api/v2/endpoint/42/log_data/', {'a': '2', 'b': 'c'}), - provider.makeUrl('endpoint', id: 42, objectMethod: 'log_data', query: {'a': '2', 'b': 'c'}), + Uri.https( + 'localhost', '/api/v2/endpoint/42/log_data/', {'a': '2', 'b': 'c'}), + provider.makeUrl('endpoint', + id: 42, objectMethod: 'log_data', query: {'a': '2', 'b': 'c'}), ); }); @@ -81,20 +85,26 @@ void main() { provider.makeUrl('endpoint', id: 5, objectMethod: 'log_data'), ); expect( - Uri.https('example.com', '/wger-url/api/v2/endpoint/', {'a': '2', 'b': 'c'}), + Uri.https( + 'example.com', '/wger-url/api/v2/endpoint/', {'a': '2', 'b': 'c'}), provider.makeUrl('endpoint', query: {'a': '2', 'b': 'c'}), ); expect( - Uri.https('example.com', '/wger-url/api/v2/endpoint/log_data/', {'a': '2', 'b': 'c'}), - provider.makeUrl('endpoint', objectMethod: 'log_data', query: {'a': '2', 'b': 'c'}), + Uri.https('example.com', '/wger-url/api/v2/endpoint/log_data/', + {'a': '2', 'b': 'c'}), + provider.makeUrl('endpoint', + objectMethod: 'log_data', query: {'a': '2', 'b': 'c'}), ); expect( - Uri.https('example.com', '/wger-url/api/v2/endpoint/42/', {'a': '2', 'b': 'c'}), + Uri.https('example.com', '/wger-url/api/v2/endpoint/42/', + {'a': '2', 'b': 'c'}), provider.makeUrl('endpoint', id: 42, query: {'a': '2', 'b': 'c'}), ); expect( - Uri.https('example.com', '/wger-url/api/v2/endpoint/42/log_data/', {'a': '2', 'b': 'c'}), - provider.makeUrl('endpoint', id: 42, objectMethod: 'log_data', query: {'a': '2', 'b': 'c'}), + Uri.https('example.com', '/wger-url/api/v2/endpoint/42/log_data/', + {'a': '2', 'b': 'c'}), + provider.makeUrl('endpoint', + id: 42, objectMethod: 'log_data', query: {'a': '2', 'b': 'c'}), ); }); }); @@ -132,7 +142,8 @@ void main() { .thenAnswer((_) => Future.value(response3)); // Act - final WgerBaseProvider provider = WgerBaseProvider(testAuthProvider, mockHttpClient); + final WgerBaseProvider provider = + WgerBaseProvider(testAuthProvider, mockHttpClient); final data = await provider.fetchPaginated(paginationUri1); // Assert diff --git a/test/other/base_provider_test.mocks.dart b/test/other/base_provider_test.mocks.dart index fef5e102c..111bf78f6 100644 --- a/test/other/base_provider_test.mocks.dart +++ b/test/other/base_provider_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/other/base_provider_test.dart. // Do not manually edit this file. @@ -19,30 +19,21 @@ import 'package:mockito/src/dummies.dart' as _i5; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { - _FakeResponse_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { - _FakeStreamedResponse_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeStreamedResponse_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [Client]. @@ -54,45 +45,27 @@ class MockClient extends _i1.Mock implements _i2.Client { } @override - _i3.Future<_i2.Response> head( - Uri? url, { - Map? headers, - }) => + _i3.Future<_i2.Response> head(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #head, - [url], - {#headers: headers}, - ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #head, - [url], - {#headers: headers}, + Invocation.method(#head, [url], {#headers: headers}), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method(#head, [url], {#headers: headers}), ), - )), + ), ) as _i3.Future<_i2.Response>); @override - _i3.Future<_i2.Response> get( - Uri? url, { - Map? headers, - }) => + _i3.Future<_i2.Response> get(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #get, - [url], - {#headers: headers}, - ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #get, - [url], - {#headers: headers}, + Invocation.method(#get, [url], {#headers: headers}), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method(#get, [url], {#headers: headers}), ), - )), + ), ) as _i3.Future<_i2.Response>); @override @@ -106,24 +79,18 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #post, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #post, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i3.Future<_i2.Response>); @override @@ -137,24 +104,18 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #put, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #put, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i3.Future<_i2.Response>); @override @@ -168,24 +129,18 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #patch, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #patch, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i3.Future<_i2.Response>); @override @@ -199,45 +154,30 @@ class MockClient extends _i1.Mock implements _i2.Client { Invocation.method( #delete, [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + {#headers: headers, #body: body, #encoding: encoding}, ), - returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0( - this, - Invocation.method( - #delete, - [url], - { - #headers: headers, - #body: body, - #encoding: encoding, - }, + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), ), - )), + ), ) as _i3.Future<_i2.Response>); @override - _i3.Future read( - Uri? url, { - Map? headers, - }) => + _i3.Future read(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method( - #read, - [url], - {#headers: headers}, - ), - returnValue: _i3.Future.value(_i5.dummyValue( - this, - Invocation.method( - #read, - [url], - {#headers: headers}, + Invocation.method(#read, [url], {#headers: headers}), + returnValue: _i3.Future.value( + _i5.dummyValue( + this, + Invocation.method(#read, [url], {#headers: headers}), ), - )), + ), ) as _i3.Future); @override @@ -246,37 +186,25 @@ class MockClient extends _i1.Mock implements _i2.Client { Map? headers, }) => (super.noSuchMethod( - Invocation.method( - #readBytes, - [url], - {#headers: headers}, - ), + Invocation.method(#readBytes, [url], {#headers: headers}), returnValue: _i3.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), ) as _i3.Future<_i6.Uint8List>); @override _i3.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => (super.noSuchMethod( - Invocation.method( - #send, - [request], - ), - returnValue: - _i3.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1( - this, - Invocation.method( - #send, - [request], + Invocation.method(#send, [request]), + returnValue: _i3.Future<_i2.StreamedResponse>.value( + _FakeStreamedResponse_1( + this, + Invocation.method(#send, [request]), ), - )), + ), ) as _i3.Future<_i2.StreamedResponse>); @override void close() => super.noSuchMethod( - Invocation.method( - #close, - [], - ), + Invocation.method(#close, []), returnValueForMissingStub: null, ); } diff --git a/test/user/provider_test.mocks.dart b/test/user/provider_test.mocks.dart index b0b9aaf6e..61a85c701 100644 --- a/test/user/provider_test.mocks.dart +++ b/test/user/provider_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/user/provider_test.dart. // Do not manually edit this file. @@ -18,49 +18,30 @@ import 'package:wger/providers/base_provider.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -74,47 +55,33 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { @override _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_0( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) as _i2.AuthProvider); @override set auth(_i2.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -129,60 +96,39 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i5.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override _i5.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i5.Future>.value([]), ) as _i5.Future>); @override - _i5.Future> post( - Map? data, - Uri? uri, - ) => + _i5.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override @@ -191,39 +137,21 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override - _i5.Future<_i3.Response> deleteRequest( - String? url, - int? id, - ) => + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i5.Future<_i3.Response>); } diff --git a/test/utils.dart b/test/utils.dart index 9244b4daa..748561638 100644 --- a/test/utils.dart +++ b/test/utils.dart @@ -23,10 +23,11 @@ import 'measurements/measurement_provider_test.mocks.dart'; import 'other/base_provider_test.mocks.dart'; // Test Auth provider -final AuthProvider testAuthProvider = AuthProvider(MockClient(), false) +final AuthProvider testAuthProvider = AuthProvider(MockClient()) ..token = 'FooBar' ..serverUrl = 'https://localhost'; // Test Exercises provider final mockBaseProvider = MockWgerBaseProvider(); -final ExercisesProvider testExercisesProvider = ExercisesProvider(mockBaseProvider); +final ExercisesProvider testExercisesProvider = + ExercisesProvider(mockBaseProvider); diff --git a/test/weight/weight_form_test.dart b/test/weight/weight_form_test.dart index 7c81ef7e7..21fe14707 100644 --- a/test/weight/weight_form_test.dart +++ b/test/weight/weight_form_test.dart @@ -34,7 +34,8 @@ void main() { ); } - testWidgets('The form is prefilled with the data from an entry', (WidgetTester tester) async { + testWidgets('The form is prefilled with the data from an entry', + (WidgetTester tester) async { await tester.pumpWidget(createWeightForm(weightEntry: testWeightEntry1)); await tester.pumpAndSettle(); @@ -42,7 +43,8 @@ void main() { expect(find.text('80'), findsOneWidget); }); - testWidgets('It is possible to quick-change the weight', (WidgetTester tester) async { + testWidgets('It is possible to quick-change the weight', + (WidgetTester tester) async { await tester.pumpWidget(createWeightForm(weightEntry: testWeightEntry1)); await tester.pumpAndSettle(); @@ -59,7 +61,8 @@ void main() { expect(find.text('80.0'), findsOneWidget); }); - testWidgets("Entering garbage doesn't break the quick-change", (WidgetTester tester) async { + testWidgets("Entering garbage doesn't break the quick-change", + (WidgetTester tester) async { await tester.pumpWidget(createWeightForm(weightEntry: testWeightEntry1)); await tester.pumpAndSettle(); await tester.enterText(find.byKey(const Key('weightInput')), 'shiba inu'); @@ -77,7 +80,8 @@ void main() { expect(find.text('shiba inu'), findsOneWidget); }); - testWidgets('Widget works if there is no last entry', (WidgetTester tester) async { + testWidgets('Widget works if there is no last entry', + (WidgetTester tester) async { await tester.pumpWidget(createWeightForm(weightEntry: null)); await tester.pumpAndSettle(); }); diff --git a/test/weight/weight_model_test.dart b/test/weight/weight_model_test.dart index 0866d83e0..9cfc9b907 100644 --- a/test/weight/weight_model_test.dart +++ b/test/weight/weight_model_test.dart @@ -22,11 +22,15 @@ import 'package:wger/models/body_weight/weight_entry.dart'; void main() { group('fetchPost', () { test('Test that the weight entries are correctly converted to json', () { - WeightEntry weightEntry = WeightEntry(id: 1, weight: 80, date: DateTime(2020, 12, 31)); - expect(weightEntry.toJson(), {'id': 1, 'weight': '80', 'date': '2020-12-31'}); + WeightEntry weightEntry = + WeightEntry(id: 1, weight: 80, date: DateTime(2020, 12, 31)); + expect(weightEntry.toJson(), + {'id': 1, 'weight': '80', 'date': '2020-12-31'}); - weightEntry = WeightEntry(id: 2, weight: 70.2, date: DateTime(2020, 12, 01)); - expect(weightEntry.toJson(), {'id': 2, 'weight': '70.2', 'date': '2020-12-01'}); + weightEntry = + WeightEntry(id: 2, weight: 70.2, date: DateTime(2020, 12, 01)); + expect(weightEntry.toJson(), + {'id': 2, 'weight': '70.2', 'date': '2020-12-01'}); }); test('Test that the weight entries are correctly converted from json', () { @@ -47,7 +51,8 @@ void main() { test('Test the individual values from the model', () { WeightEntry weightModel; //_weightModel = WeightEntry(); - weightModel = WeightEntry(id: 1, weight: 80, date: DateTime(2020, 10, 01)); + weightModel = + WeightEntry(id: 1, weight: 80, date: DateTime(2020, 10, 01)); expect(weightModel.id, 1); expect(weightModel.weight, 80); diff --git a/test/weight/weight_provider_test.dart b/test/weight/weight_provider_test.dart index 08ce8c669..cafd244e9 100644 --- a/test/weight/weight_provider_test.dart +++ b/test/weight/weight_provider_test.dart @@ -44,7 +44,8 @@ void main() { host: 'localhost', path: 'api/v2/weightentry/', ); - when(mockBaseProvider.makeUrl(any, query: anyNamed('query'))).thenReturn(uri); + when(mockBaseProvider.makeUrl(any, query: anyNamed('query'))) + .thenReturn(uri); final Map weightEntries = jsonDecode( fixture('weight/weight_entries.json'), ); @@ -69,13 +70,17 @@ void main() { host: 'localhost', path: 'api/v2/weightentry/', ); - when(mockBaseProvider.makeUrl(any, query: anyNamed('query'))).thenReturn(uri); - when(mockBaseProvider.post({'id': null, 'weight': '80', 'date': '2021-01-01'}, uri)) - .thenAnswer((_) => Future.value({'id': 25, 'date': '2021-01-01', 'weight': '80'})); + when(mockBaseProvider.makeUrl(any, query: anyNamed('query'))) + .thenReturn(uri); + when(mockBaseProvider + .post({'id': null, 'weight': '80', 'date': '2021-01-01'}, uri)) + .thenAnswer((_) => + Future.value({'id': 25, 'date': '2021-01-01', 'weight': '80'})); // Act final BodyWeightProvider provider = BodyWeightProvider(mockBaseProvider); - final WeightEntry weightEntry = WeightEntry(date: DateTime(2021, 1, 1), weight: 80); + final WeightEntry weightEntry = + WeightEntry(date: DateTime(2021, 1, 1), weight: 80); final WeightEntry weightEntryNew = await provider.addEntry(weightEntry); // Assert @@ -91,9 +96,11 @@ void main() { host: 'localhost', path: 'api/v2/weightentry/4/', ); - when(mockBaseProvider.makeUrl(any, query: anyNamed('query'))).thenReturn(uri); + when(mockBaseProvider.makeUrl(any, query: anyNamed('query'))) + .thenReturn(uri); when(mockBaseProvider.deleteRequest('weightentry', 4)).thenAnswer( - (_) => Future.value(Response("{'id': 4, 'date': '2021-01-01', 'weight': '80'}", 204)), + (_) => Future.value( + Response("{'id': 4, 'date': '2021-01-01', 'weight': '80'}", 204)), ); // DELETE the data from the server diff --git a/test/weight/weight_provider_test.mocks.dart b/test/weight/weight_provider_test.mocks.dart index 8c8530b68..5d090f56d 100644 --- a/test/weight/weight_provider_test.mocks.dart +++ b/test/weight/weight_provider_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/weight/weight_provider_test.dart. // Do not manually edit this file. @@ -18,49 +18,30 @@ import 'package:wger/providers/base_provider.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -74,47 +55,33 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { @override _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_0( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) as _i2.AuthProvider); @override set auth(_i2.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -129,60 +96,39 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i5.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override _i5.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i5.Future>.value([]), ) as _i5.Future>); @override - _i5.Future> post( - Map? data, - Uri? uri, - ) => + _i5.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override @@ -191,39 +137,21 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override - _i5.Future<_i3.Response> deleteRequest( - String? url, - int? id, - ) => + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i5.Future<_i3.Response>); } diff --git a/test/weight/weight_screen_test.mocks.dart b/test/weight/weight_screen_test.mocks.dart index e0cea4f37..db31506ca 100644 --- a/test/weight/weight_screen_test.mocks.dart +++ b/test/weight/weight_screen_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/weight/weight_screen_test.dart. // Do not manually edit this file. @@ -28,6 +28,7 @@ import 'package:wger/providers/user.dart' as _i12; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -35,75 +36,40 @@ import 'package:wger/providers/user.dart' as _i12; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWeightEntry_1 extends _i1.SmartFake implements _i3.WeightEntry { - _FakeWeightEntry_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWeightEntry_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIngredientDatabase_2 extends _i1.SmartFake implements _i4.IngredientDatabase { - _FakeIngredientDatabase_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIngredientDatabase_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeNutritionalPlan_3 extends _i1.SmartFake implements _i5.NutritionalPlan { - _FakeNutritionalPlan_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeNutritionalPlan_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMeal_4 extends _i1.SmartFake implements _i6.Meal { - _FakeMeal_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMeal_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMealItem_5 extends _i1.SmartFake implements _i7.MealItem { - _FakeMealItem_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMealItem_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeIngredient_6 extends _i1.SmartFake implements _i8.Ingredient { - _FakeIngredient_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeIngredient_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [BodyWeightProvider]. @@ -132,130 +98,88 @@ class MockBodyWeightProvider extends _i1.Mock @override set items(List<_i3.WeightEntry>? entries) => super.noSuchMethod( - Invocation.setter( - #items, - entries, - ), + Invocation.setter(#items, entries), returnValueForMissingStub: null, ); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i3.WeightEntry findById(int? id) => (super.noSuchMethod( - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), returnValue: _FakeWeightEntry_1( this, - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), ), ) as _i3.WeightEntry); @override _i3.WeightEntry? findByDate(DateTime? date) => - (super.noSuchMethod(Invocation.method( - #findByDate, - [date], - )) as _i3.WeightEntry?); + (super.noSuchMethod(Invocation.method(#findByDate, [date])) + as _i3.WeightEntry?); @override _i10.Future> fetchAndSetEntries() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetEntries, - [], + Invocation.method(#fetchAndSetEntries, []), + returnValue: _i10.Future>.value( + <_i3.WeightEntry>[], ), - returnValue: - _i10.Future>.value(<_i3.WeightEntry>[]), ) as _i10.Future>); @override _i10.Future<_i3.WeightEntry> addEntry(_i3.WeightEntry? entry) => (super.noSuchMethod( - Invocation.method( - #addEntry, - [entry], + Invocation.method(#addEntry, [entry]), + returnValue: _i10.Future<_i3.WeightEntry>.value( + _FakeWeightEntry_1(this, Invocation.method(#addEntry, [entry])), ), - returnValue: _i10.Future<_i3.WeightEntry>.value(_FakeWeightEntry_1( - this, - Invocation.method( - #addEntry, - [entry], - ), - )), ) as _i10.Future<_i3.WeightEntry>); @override _i10.Future editEntry(_i3.WeightEntry? entry) => (super.noSuchMethod( - Invocation.method( - #editEntry, - [entry], - ), + Invocation.method(#editEntry, [entry]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override _i10.Future deleteEntry(int? id) => (super.noSuchMethod( - Invocation.method( - #deleteEntry, - [id], - ), + Invocation.method(#deleteEntry, [id]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override void addListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } @@ -279,91 +203,63 @@ class MockUserProvider extends _i1.Mock implements _i12.UserProvider { @override set profile(_i13.Profile? _profile) => super.noSuchMethod( - Invocation.setter( - #profile, - _profile, - ), + Invocation.setter(#profile, _profile), returnValueForMissingStub: null, ); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i10.Future fetchAndSetProfile() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetProfile, - [], - ), + Invocation.method(#fetchAndSetProfile, []), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override _i10.Future saveProfile() => (super.noSuchMethod( - Invocation.method( - #saveProfile, - [], - ), + Invocation.method(#saveProfile, []), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override _i10.Future verifyEmail() => (super.noSuchMethod( - Invocation.method( - #verifyEmail, - [], - ), + Invocation.method(#verifyEmail, []), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override void addListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } @@ -397,10 +293,7 @@ class MockNutritionPlansProvider extends _i1.Mock @override set database(_i4.IngredientDatabase? _database) => super.noSuchMethod( - Invocation.setter( - #database, - _database, - ), + Invocation.setter(#database, _database), returnValueForMissingStub: null, ); @@ -412,10 +305,7 @@ class MockNutritionPlansProvider extends _i1.Mock @override set ingredients(List<_i8.Ingredient>? _ingredients) => super.noSuchMethod( - Invocation.setter( - #ingredients, - _ingredients, - ), + Invocation.setter(#ingredients, _ingredients), returnValueForMissingStub: null, ); @@ -426,57 +316,39 @@ class MockNutritionPlansProvider extends _i1.Mock ) as List<_i5.NutritionalPlan>); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i5.NutritionalPlan findById(int? id) => (super.noSuchMethod( - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), returnValue: _FakeNutritionalPlan_3( this, - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), ), ) as _i5.NutritionalPlan); @override - _i6.Meal? findMealById(int? id) => (super.noSuchMethod(Invocation.method( - #findMealById, - [id], - )) as _i6.Meal?); + _i6.Meal? findMealById(int? id) => + (super.noSuchMethod(Invocation.method(#findMealById, [id])) as _i6.Meal?); @override _i10.Future fetchAndSetAllPlansSparse() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansSparse, - [], - ), + Invocation.method(#fetchAndSetAllPlansSparse, []), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override _i10.Future fetchAndSetAllPlansFull() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansFull, - [], - ), + Invocation.method(#fetchAndSetAllPlansFull, []), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @@ -484,120 +356,73 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i10.Future<_i5.NutritionalPlan> fetchAndSetPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanSparse, - [planId], - ), - returnValue: - _i10.Future<_i5.NutritionalPlan>.value(_FakeNutritionalPlan_3( - this, - Invocation.method( - #fetchAndSetPlanSparse, - [planId], + Invocation.method(#fetchAndSetPlanSparse, [planId]), + returnValue: _i10.Future<_i5.NutritionalPlan>.value( + _FakeNutritionalPlan_3( + this, + Invocation.method(#fetchAndSetPlanSparse, [planId]), ), - )), + ), ) as _i10.Future<_i5.NutritionalPlan>); @override _i10.Future<_i5.NutritionalPlan> fetchAndSetPlanFull(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanFull, - [planId], - ), - returnValue: - _i10.Future<_i5.NutritionalPlan>.value(_FakeNutritionalPlan_3( - this, - Invocation.method( - #fetchAndSetPlanFull, - [planId], + Invocation.method(#fetchAndSetPlanFull, [planId]), + returnValue: _i10.Future<_i5.NutritionalPlan>.value( + _FakeNutritionalPlan_3( + this, + Invocation.method(#fetchAndSetPlanFull, [planId]), ), - )), + ), ) as _i10.Future<_i5.NutritionalPlan>); @override _i10.Future<_i5.NutritionalPlan> addPlan(_i5.NutritionalPlan? planData) => (super.noSuchMethod( - Invocation.method( - #addPlan, - [planData], - ), - returnValue: - _i10.Future<_i5.NutritionalPlan>.value(_FakeNutritionalPlan_3( - this, - Invocation.method( - #addPlan, - [planData], + Invocation.method(#addPlan, [planData]), + returnValue: _i10.Future<_i5.NutritionalPlan>.value( + _FakeNutritionalPlan_3( + this, + Invocation.method(#addPlan, [planData]), ), - )), + ), ) as _i10.Future<_i5.NutritionalPlan>); @override _i10.Future editPlan(_i5.NutritionalPlan? plan) => (super.noSuchMethod( - Invocation.method( - #editPlan, - [plan], - ), + Invocation.method(#editPlan, [plan]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override _i10.Future deletePlan(int? id) => (super.noSuchMethod( - Invocation.method( - #deletePlan, - [id], - ), + Invocation.method(#deletePlan, [id]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override - _i10.Future<_i6.Meal> addMeal( - _i6.Meal? meal, - int? planId, - ) => + _i10.Future<_i6.Meal> addMeal(_i6.Meal? meal, int? planId) => (super.noSuchMethod( - Invocation.method( - #addMeal, - [ - meal, - planId, - ], + Invocation.method(#addMeal, [meal, planId]), + returnValue: _i10.Future<_i6.Meal>.value( + _FakeMeal_4(this, Invocation.method(#addMeal, [meal, planId])), ), - returnValue: _i10.Future<_i6.Meal>.value(_FakeMeal_4( - this, - Invocation.method( - #addMeal, - [ - meal, - planId, - ], - ), - )), ) as _i10.Future<_i6.Meal>); @override _i10.Future<_i6.Meal> editMeal(_i6.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #editMeal, - [meal], + Invocation.method(#editMeal, [meal]), + returnValue: _i10.Future<_i6.Meal>.value( + _FakeMeal_4(this, Invocation.method(#editMeal, [meal])), ), - returnValue: _i10.Future<_i6.Meal>.value(_FakeMeal_4( - this, - Invocation.method( - #editMeal, - [meal], - ), - )), ) as _i10.Future<_i6.Meal>); @override _i10.Future deleteMeal(_i6.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #deleteMeal, - [meal], - ), + Invocation.method(#deleteMeal, [meal]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @@ -608,42 +433,26 @@ class MockNutritionPlansProvider extends _i1.Mock _i6.Meal? meal, ) => (super.noSuchMethod( - Invocation.method( - #addMealItem, - [ - mealItem, - meal, - ], - ), - returnValue: _i10.Future<_i7.MealItem>.value(_FakeMealItem_5( - this, - Invocation.method( - #addMealItem, - [ - mealItem, - meal, - ], + Invocation.method(#addMealItem, [mealItem, meal]), + returnValue: _i10.Future<_i7.MealItem>.value( + _FakeMealItem_5( + this, + Invocation.method(#addMealItem, [mealItem, meal]), ), - )), + ), ) as _i10.Future<_i7.MealItem>); @override _i10.Future deleteMealItem(_i7.MealItem? mealItem) => (super.noSuchMethod( - Invocation.method( - #deleteMealItem, - [mealItem], - ), + Invocation.method(#deleteMealItem, [mealItem]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override _i10.Future clearIngredientCache() => (super.noSuchMethod( - Invocation.method( - #clearIngredientCache, - [], - ), + Invocation.method(#clearIngredientCache, []), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @@ -659,22 +468,21 @@ class MockNutritionPlansProvider extends _i1.Mock [ingredientId], {#database: database}, ), - returnValue: _i10.Future<_i8.Ingredient>.value(_FakeIngredient_6( - this, - Invocation.method( - #fetchIngredient, - [ingredientId], - {#database: database}, + returnValue: _i10.Future<_i8.Ingredient>.value( + _FakeIngredient_6( + this, + Invocation.method( + #fetchIngredient, + [ingredientId], + {#database: database}, + ), ), - )), + ), ) as _i10.Future<_i8.Ingredient>); @override _i10.Future fetchIngredientsFromCache() => (super.noSuchMethod( - Invocation.method( - #fetchIngredientsFromCache, - [], - ), + Invocation.method(#fetchIngredientsFromCache, []), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @@ -682,38 +490,30 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i10.Future> searchIngredient( String? name, { - String? languageCode = r'en', + String? languageCode = 'en', bool? searchEnglish = false, }) => (super.noSuchMethod( Invocation.method( #searchIngredient, [name], - { - #languageCode: languageCode, - #searchEnglish: searchEnglish, - }, + {#languageCode: languageCode, #searchEnglish: searchEnglish}, ), returnValue: _i10.Future>.value( - <_i15.IngredientApiSearchEntry>[]), + <_i15.IngredientApiSearchEntry>[], + ), ) as _i10.Future>); @override _i10.Future<_i8.Ingredient?> searchIngredientWithCode(String? code) => (super.noSuchMethod( - Invocation.method( - #searchIngredientWithCode, - [code], - ), + Invocation.method(#searchIngredientWithCode, [code]), returnValue: _i10.Future<_i8.Ingredient?>.value(), ) as _i10.Future<_i8.Ingredient?>); @override _i10.Future logMealToDiary(_i6.Meal? meal) => (super.noSuchMethod( - Invocation.method( - #logMealToDiary, - [meal], - ), + Invocation.method(#logMealToDiary, [meal]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @@ -725,31 +525,18 @@ class MockNutritionPlansProvider extends _i1.Mock DateTime? dateTime, ]) => (super.noSuchMethod( - Invocation.method( - #logIngredientToDiary, - [ - mealItem, - planId, - dateTime, - ], - ), + Invocation.method(#logIngredientToDiary, [ + mealItem, + planId, + dateTime, + ]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override - _i10.Future deleteLog( - int? logId, - int? planId, - ) => - (super.noSuchMethod( - Invocation.method( - #deleteLog, - [ - logId, - planId, - ], - ), + _i10.Future deleteLog(int? logId, int? planId) => (super.noSuchMethod( + Invocation.method(#deleteLog, [logId, planId]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @@ -757,47 +544,32 @@ class MockNutritionPlansProvider extends _i1.Mock @override _i10.Future fetchAndSetLogs(_i5.NutritionalPlan? plan) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetLogs, - [plan], - ), + Invocation.method(#fetchAndSetLogs, [plan]), returnValue: _i10.Future.value(), returnValueForMissingStub: _i10.Future.value(), ) as _i10.Future); @override void addListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i11.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/workout/gym_mode_screen_test.dart b/test/workout/gym_mode_screen_test.dart index 5175ef8da..0340ce536 100644 --- a/test/workout/gym_mode_screen_test.dart +++ b/test/workout/gym_mode_screen_test.dart @@ -74,7 +74,8 @@ void main() { ); } - testWidgets('Test the widgets on the gym mode screen', (WidgetTester tester) async { + testWidgets('Test the widgets on the gym mode screen', + (WidgetTester tester) async { when(mockExerciseProvider.findExerciseById(1)).thenReturn(bases[0]); when(mockExerciseProvider.findExerciseById(6)).thenReturn(bases[5]); @@ -114,10 +115,12 @@ void main() { expect(find.text('Bench press'), findsOneWidget); expect(find.byType(LogPage), findsOneWidget); expect(find.byType(Form), findsOneWidget); - expect(find.byType(ListTile), findsNWidgets(3), reason: 'Two logs and the switch tile'); + expect(find.byType(ListTile), findsNWidgets(3), + reason: 'Two logs and the switch tile'); expect(find.text('10 × 10 kg (1.5 RiR)'), findsOneWidget); expect(find.text('12 × 10 kg (2 RiR)'), findsOneWidget); - expect(find.text('Make sure to warm up'), findsOneWidget, reason: 'Set comment'); + expect(find.text('Make sure to warm up'), findsOneWidget, + reason: 'Set comment'); expect(find.byIcon(Icons.close), findsOneWidget); expect(find.byIcon(Icons.toc), findsOneWidget); expect(find.byIcon(Icons.chevron_left), findsOneWidget); diff --git a/test/workout/gym_mode_screen_test.mocks.dart b/test/workout/gym_mode_screen_test.mocks.dart index 5647a1f0e..435fdfd04 100644 --- a/test/workout/gym_mode_screen_test.mocks.dart +++ b/test/workout/gym_mode_screen_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/workout/gym_mode_screen_test.dart. // Do not manually edit this file. @@ -26,122 +26,68 @@ import 'package:wger/providers/exercises.dart' as _i12; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWgerBaseProvider_4 extends _i1.SmartFake implements _i4.WgerBaseProvider { - _FakeWgerBaseProvider_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExerciseDatabase_5 extends _i1.SmartFake implements _i5.ExerciseDatabase { - _FakeExerciseDatabase_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeExerciseDatabase_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExercise_6 extends _i1.SmartFake implements _i6.Exercise { - _FakeExercise_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeExercise_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExerciseCategory_7 extends _i1.SmartFake implements _i7.ExerciseCategory { - _FakeExerciseCategory_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeExerciseCategory_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeEquipment_8 extends _i1.SmartFake implements _i8.Equipment { - _FakeEquipment_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeEquipment_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMuscle_9 extends _i1.SmartFake implements _i9.Muscle { - _FakeMuscle_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMuscle_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeLanguage_10 extends _i1.SmartFake implements _i10.Language { - _FakeLanguage_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeLanguage_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -155,47 +101,33 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { @override _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_0( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) as _i2.AuthProvider); @override set auth(_i2.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -210,42 +142,29 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i11.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i11.Future>.value( + {}, ), - returnValue: - _i11.Future>.value({}), ) as _i11.Future>); @override _i11.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i11.Future>.value([]), ) as _i11.Future>); @@ -255,15 +174,10 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i11.Future>.value( + {}, ), - returnValue: - _i11.Future>.value({}), ) as _i11.Future>); @override @@ -272,40 +186,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i11.Future>.value( + {}, ), - returnValue: - _i11.Future>.value({}), ) as _i11.Future>); @override - _i11.Future<_i3.Response> deleteRequest( - String? url, - int? id, - ) => + _i11.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i11.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i11.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i11.Future<_i3.Response>); } @@ -337,10 +233,7 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override set database(_i5.ExerciseDatabase? _database) => super.noSuchMethod( - Invocation.setter( - #database, - _database, - ), + Invocation.setter(#database, _database), returnValueForMissingStub: null, ); @@ -352,10 +245,7 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override set exercises(List<_i6.Exercise>? _exercises) => super.noSuchMethod( - Invocation.setter( - #exercises, - _exercises, - ), + Invocation.setter(#exercises, _exercises), returnValueForMissingStub: null, ); @@ -368,10 +258,7 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override set filteredExercises(List<_i6.Exercise>? newFilteredExercises) => super.noSuchMethod( - Invocation.setter( - #filteredExercises, - newFilteredExercises, - ), + Invocation.setter(#filteredExercises, newFilteredExercises), returnValueForMissingStub: null, ); @@ -408,69 +295,47 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override set languages(List<_i10.Language>? languages) => super.noSuchMethod( - Invocation.setter( - #languages, - languages, - ), + Invocation.setter(#languages, languages), returnValueForMissingStub: null, ); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override _i11.Future setFilters(_i12.Filters? newFilters) => (super.noSuchMethod( - Invocation.method( - #setFilters, - [newFilters], - ), + Invocation.method(#setFilters, [newFilters]), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @override void initFilters() => super.noSuchMethod( - Invocation.method( - #initFilters, - [], - ), + Invocation.method(#initFilters, []), returnValueForMissingStub: null, ); @override _i11.Future findByFilters() => (super.noSuchMethod( - Invocation.method( - #findByFilters, - [], - ), + Invocation.method(#findByFilters, []), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i6.Exercise findExerciseById(int? id) => (super.noSuchMethod( - Invocation.method( - #findExerciseById, - [id], - ), + Invocation.method(#findExerciseById, [id]), returnValue: _FakeExercise_6( this, - Invocation.method( - #findExerciseById, - [id], - ), + Invocation.method(#findExerciseById, [id]), ), ) as _i6.Exercise); @@ -490,100 +355,64 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override _i7.ExerciseCategory findCategoryById(int? id) => (super.noSuchMethod( - Invocation.method( - #findCategoryById, - [id], - ), + Invocation.method(#findCategoryById, [id]), returnValue: _FakeExerciseCategory_7( this, - Invocation.method( - #findCategoryById, - [id], - ), + Invocation.method(#findCategoryById, [id]), ), ) as _i7.ExerciseCategory); @override _i8.Equipment findEquipmentById(int? id) => (super.noSuchMethod( - Invocation.method( - #findEquipmentById, - [id], - ), + Invocation.method(#findEquipmentById, [id]), returnValue: _FakeEquipment_8( this, - Invocation.method( - #findEquipmentById, - [id], - ), + Invocation.method(#findEquipmentById, [id]), ), ) as _i8.Equipment); @override _i9.Muscle findMuscleById(int? id) => (super.noSuchMethod( - Invocation.method( - #findMuscleById, - [id], - ), + Invocation.method(#findMuscleById, [id]), returnValue: _FakeMuscle_9( this, - Invocation.method( - #findMuscleById, - [id], - ), + Invocation.method(#findMuscleById, [id]), ), ) as _i9.Muscle); @override _i10.Language findLanguageById(int? id) => (super.noSuchMethod( - Invocation.method( - #findLanguageById, - [id], - ), + Invocation.method(#findLanguageById, [id]), returnValue: _FakeLanguage_10( this, - Invocation.method( - #findLanguageById, - [id], - ), + Invocation.method(#findLanguageById, [id]), ), ) as _i10.Language); @override _i11.Future fetchAndSetCategoriesFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetCategoriesFromApi, - [], - ), + Invocation.method(#fetchAndSetCategoriesFromApi, []), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @override _i11.Future fetchAndSetMusclesFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetMusclesFromApi, - [], - ), + Invocation.method(#fetchAndSetMusclesFromApi, []), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @override _i11.Future fetchAndSetEquipmentsFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetEquipmentsFromApi, - [], - ), + Invocation.method(#fetchAndSetEquipmentsFromApi, []), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @override _i11.Future fetchAndSetLanguagesFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetLanguagesFromApi, - [], - ), + Invocation.method(#fetchAndSetLanguagesFromApi, []), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @@ -591,17 +420,13 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override _i11.Future<_i6.Exercise> fetchAndSetExercise(int? exerciseId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetExercise, - [exerciseId], - ), - returnValue: _i11.Future<_i6.Exercise>.value(_FakeExercise_6( - this, - Invocation.method( - #fetchAndSetExercise, - [exerciseId], + Invocation.method(#fetchAndSetExercise, [exerciseId]), + returnValue: _i11.Future<_i6.Exercise>.value( + _FakeExercise_6( + this, + Invocation.method(#fetchAndSetExercise, [exerciseId]), ), - )), + ), ) as _i11.Future<_i6.Exercise>); @override @@ -610,53 +435,41 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { int? exerciseId, ) => (super.noSuchMethod( - Invocation.method( - #handleUpdateExerciseFromApi, - [ - database, - exerciseId, - ], - ), - returnValue: _i11.Future<_i6.Exercise>.value(_FakeExercise_6( - this, - Invocation.method( - #handleUpdateExerciseFromApi, - [ + Invocation.method(#handleUpdateExerciseFromApi, [ + database, + exerciseId, + ]), + returnValue: _i11.Future<_i6.Exercise>.value( + _FakeExercise_6( + this, + Invocation.method(#handleUpdateExerciseFromApi, [ database, exerciseId, - ], + ]), ), - )), + ), ) as _i11.Future<_i6.Exercise>); @override _i11.Future initCacheTimesLocalPrefs({dynamic forceInit = false}) => (super.noSuchMethod( - Invocation.method( - #initCacheTimesLocalPrefs, - [], - {#forceInit: forceInit}, - ), + Invocation.method(#initCacheTimesLocalPrefs, [], { + #forceInit: forceInit, + }), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @override _i11.Future clearAllCachesAndPrefs() => (super.noSuchMethod( - Invocation.method( - #clearAllCachesAndPrefs, - [], - ), + Invocation.method(#clearAllCachesAndPrefs, []), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @override _i11.Future fetchAndSetInitialData() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetInitialData, - [], - ), + Invocation.method(#fetchAndSetInitialData, []), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @@ -679,10 +492,7 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override _i11.Future updateExerciseCache(_i5.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #updateExerciseCache, - [database], - ), + Invocation.method(#updateExerciseCache, [database]), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @@ -690,10 +500,7 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override _i11.Future fetchAndSetMuscles(_i5.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetMuscles, - [database], - ), + Invocation.method(#fetchAndSetMuscles, [database]), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @@ -701,10 +508,7 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override _i11.Future fetchAndSetCategories(_i5.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetCategories, - [database], - ), + Invocation.method(#fetchAndSetCategories, [database]), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @@ -712,10 +516,7 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override _i11.Future fetchAndSetLanguages(_i5.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetLanguages, - [database], - ), + Invocation.method(#fetchAndSetLanguages, [database]), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @@ -723,10 +524,7 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override _i11.Future fetchAndSetEquipments(_i5.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetEquipments, - [database], - ), + Invocation.method(#fetchAndSetEquipments, [database]), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(), ) as _i11.Future); @@ -734,54 +532,41 @@ class MockExercisesProvider extends _i1.Mock implements _i12.ExercisesProvider { @override _i11.Future> searchExercise( String? name, { - String? languageCode = r'en', + String? languageCode = 'en', bool? searchEnglish = false, }) => (super.noSuchMethod( Invocation.method( #searchExercise, [name], - { - #languageCode: languageCode, - #searchEnglish: searchEnglish, - }, + {#languageCode: languageCode, #searchEnglish: searchEnglish}, + ), + returnValue: _i11.Future>.value( + <_i6.Exercise>[], ), - returnValue: _i11.Future>.value(<_i6.Exercise>[]), ) as _i11.Future>); @override void addListener(_i13.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i13.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/workout/plate_calculator_test.dart b/test/workout/plate_calculator_test.dart index 60a1b017b..f64c9e668 100644 --- a/test/workout/plate_calculator_test.dart +++ b/test/workout/plate_calculator_test.dart @@ -25,8 +25,10 @@ void main() { test('Regular weights', () { expect(plateCalculator(40, BAR_WEIGHT, AVAILABLE_PLATES), [10]); expect(plateCalculator(100, BAR_WEIGHT, AVAILABLE_PLATES), [15, 15, 10]); - expect(plateCalculator(102.5, BAR_WEIGHT, AVAILABLE_PLATES), [15, 15, 10, 1.25]); - expect(plateCalculator(140, BAR_WEIGHT, AVAILABLE_PLATES), [15, 15, 15, 15]); + expect(plateCalculator(102.5, BAR_WEIGHT, AVAILABLE_PLATES), + [15, 15, 10, 1.25]); + expect( + plateCalculator(140, BAR_WEIGHT, AVAILABLE_PLATES), [15, 15, 15, 15]); expect(plateCalculator(45, BAR_WEIGHT, AVAILABLE_PLATES), [10, 2.5]); expect(plateCalculator(85, BAR_WEIGHT, AVAILABLE_PLATES), [15, 15, 2.5]); }); diff --git a/test/workout/repetition_unit_form_widget_test.dart b/test/workout/repetition_unit_form_widget_test.dart index 423860073..b6d6e4618 100644 --- a/test/workout/repetition_unit_form_widget_test.dart +++ b/test/workout/repetition_unit_form_widget_test.dart @@ -52,7 +52,8 @@ void main() { setUp(() { mockWorkoutPlans = MockWorkoutPlansProvider(); - when(mockWorkoutPlans.repetitionUnits).thenAnswer((_) => [unit1, unit2, unit3]); + when(mockWorkoutPlans.repetitionUnits) + .thenAnswer((_) => [unit1, unit2, unit3]); }); Widget createHomeScreen() { @@ -84,7 +85,8 @@ void main() { expect(find.text('this is repetition number 3'), findsWidgets); }); - testWidgets('Test that the correct units are set after selection', (WidgetTester tester) async { + testWidgets('Test that the correct units are set after selection', + (WidgetTester tester) async { // arrange await tester.pumpWidget(createHomeScreen()); await tester.pump(); diff --git a/test/workout/repetition_unit_form_widget_test.mocks.dart b/test/workout/repetition_unit_form_widget_test.mocks.dart index 85af2f8a1..817d1f7a0 100644 --- a/test/workout/repetition_unit_form_widget_test.mocks.dart +++ b/test/workout/repetition_unit_form_widget_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/workout/repetition_unit_form_widget_test.dart. // Do not manually edit this file. @@ -29,6 +29,7 @@ import 'package:wger/providers/workout_plans.dart' as _i11; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -36,95 +37,50 @@ import 'package:wger/providers/workout_plans.dart' as _i11; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWeightUnit_1 extends _i1.SmartFake implements _i3.WeightUnit { - _FakeWeightUnit_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWeightUnit_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeRepetitionUnit_2 extends _i1.SmartFake implements _i4.RepetitionUnit { - _FakeRepetitionUnit_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeRepetitionUnit_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWorkoutPlan_3 extends _i1.SmartFake implements _i5.WorkoutPlan { - _FakeWorkoutPlan_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWorkoutPlan_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDay_4 extends _i1.SmartFake implements _i6.Day { - _FakeDay_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDay_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSet_5 extends _i1.SmartFake implements _i7.Set { - _FakeSet_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSet_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSetting_6 extends _i1.SmartFake implements _i8.Setting { - _FakeSetting_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSetting_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWorkoutSession_7 extends _i1.SmartFake implements _i9.WorkoutSession { - _FakeWorkoutSession_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWorkoutSession_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeLog_8 extends _i1.SmartFake implements _i10.Log { - _FakeLog_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeLog_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WorkoutPlansProvider]. @@ -182,87 +138,59 @@ class MockWorkoutPlansProvider extends _i1.Mock ) as _i4.RepetitionUnit); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override List<_i5.WorkoutPlan> getPlans() => (super.noSuchMethod( - Invocation.method( - #getPlans, - [], - ), + Invocation.method(#getPlans, []), returnValue: <_i5.WorkoutPlan>[], ) as List<_i5.WorkoutPlan>); @override _i5.WorkoutPlan findById(int? id) => (super.noSuchMethod( - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), returnValue: _FakeWorkoutPlan_3( this, - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), ), ) as _i5.WorkoutPlan); @override int findIndexById(int? id) => (super.noSuchMethod( - Invocation.method( - #findIndexById, - [id], - ), + Invocation.method(#findIndexById, [id]), returnValue: 0, ) as int); @override void setCurrentPlan(int? id) => super.noSuchMethod( - Invocation.method( - #setCurrentPlan, - [id], - ), + Invocation.method(#setCurrentPlan, [id]), returnValueForMissingStub: null, ); @override void resetCurrentPlan() => super.noSuchMethod( - Invocation.method( - #resetCurrentPlan, - [], - ), + Invocation.method(#resetCurrentPlan, []), returnValueForMissingStub: null, ); @override _i12.Future fetchAndSetAllPlansFull() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansFull, - [], - ), + Invocation.method(#fetchAndSetAllPlansFull, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future fetchAndSetAllPlansSparse() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansSparse, - [], - ), + Invocation.method(#fetchAndSetAllPlansSparse, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -270,68 +198,50 @@ class MockWorkoutPlansProvider extends _i1.Mock @override _i12.Future<_i5.WorkoutPlan> fetchAndSetPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanSparse, - [planId], - ), - returnValue: _i12.Future<_i5.WorkoutPlan>.value(_FakeWorkoutPlan_3( - this, - Invocation.method( - #fetchAndSetPlanSparse, - [planId], + Invocation.method(#fetchAndSetPlanSparse, [planId]), + returnValue: _i12.Future<_i5.WorkoutPlan>.value( + _FakeWorkoutPlan_3( + this, + Invocation.method(#fetchAndSetPlanSparse, [planId]), ), - )), + ), ) as _i12.Future<_i5.WorkoutPlan>); @override _i12.Future<_i5.WorkoutPlan> fetchAndSetWorkoutPlanFull(int? workoutId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetWorkoutPlanFull, - [workoutId], - ), - returnValue: _i12.Future<_i5.WorkoutPlan>.value(_FakeWorkoutPlan_3( - this, - Invocation.method( - #fetchAndSetWorkoutPlanFull, - [workoutId], + Invocation.method(#fetchAndSetWorkoutPlanFull, [workoutId]), + returnValue: _i12.Future<_i5.WorkoutPlan>.value( + _FakeWorkoutPlan_3( + this, + Invocation.method(#fetchAndSetWorkoutPlanFull, [workoutId]), ), - )), + ), ) as _i12.Future<_i5.WorkoutPlan>); @override _i12.Future<_i5.WorkoutPlan> addWorkout(_i5.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #addWorkout, - [workout], - ), - returnValue: _i12.Future<_i5.WorkoutPlan>.value(_FakeWorkoutPlan_3( - this, - Invocation.method( - #addWorkout, - [workout], + Invocation.method(#addWorkout, [workout]), + returnValue: _i12.Future<_i5.WorkoutPlan>.value( + _FakeWorkoutPlan_3( + this, + Invocation.method(#addWorkout, [workout]), ), - )), + ), ) as _i12.Future<_i5.WorkoutPlan>); @override _i12.Future editWorkout(_i5.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #editWorkout, - [workout], - ), + Invocation.method(#editWorkout, [workout]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future deleteWorkout(int? id) => (super.noSuchMethod( - Invocation.method( - #deleteWorkout, - [id], - ), + Invocation.method(#deleteWorkout, [id]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -342,113 +252,67 @@ class MockWorkoutPlansProvider extends _i1.Mock _i13.Exercise? base, ) => (super.noSuchMethod( - Invocation.method( - #fetchLogData, - [ - workout, - base, - ], + Invocation.method(#fetchLogData, [workout, base]), + returnValue: _i12.Future>.value( + {}, ), - returnValue: - _i12.Future>.value({}), ) as _i12.Future>); @override _i12.Future fetchAndSetRepetitionUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetRepetitionUnits, - [], - ), + Invocation.method(#fetchAndSetRepetitionUnits, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future fetchAndSetWeightUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetWeightUnits, - [], - ), + Invocation.method(#fetchAndSetWeightUnits, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future fetchAndSetUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetUnits, - [], - ), + Invocation.method(#fetchAndSetUnits, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override - _i12.Future<_i6.Day> addDay( - _i6.Day? day, - _i5.WorkoutPlan? workout, - ) => + _i12.Future<_i6.Day> addDay(_i6.Day? day, _i5.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #addDay, - [ - day, - workout, - ], + Invocation.method(#addDay, [day, workout]), + returnValue: _i12.Future<_i6.Day>.value( + _FakeDay_4(this, Invocation.method(#addDay, [day, workout])), ), - returnValue: _i12.Future<_i6.Day>.value(_FakeDay_4( - this, - Invocation.method( - #addDay, - [ - day, - workout, - ], - ), - )), ) as _i12.Future<_i6.Day>); @override _i12.Future editDay(_i6.Day? day) => (super.noSuchMethod( - Invocation.method( - #editDay, - [day], - ), + Invocation.method(#editDay, [day]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future deleteDay(_i6.Day? day) => (super.noSuchMethod( - Invocation.method( - #deleteDay, - [day], - ), + Invocation.method(#deleteDay, [day]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future<_i7.Set> addSet(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #addSet, - [workoutSet], + Invocation.method(#addSet, [workoutSet]), + returnValue: _i12.Future<_i7.Set>.value( + _FakeSet_5(this, Invocation.method(#addSet, [workoutSet])), ), - returnValue: _i12.Future<_i7.Set>.value(_FakeSet_5( - this, - Invocation.method( - #addSet, - [workoutSet], - ), - )), ) as _i12.Future<_i7.Set>); @override _i12.Future editSet(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #editSet, - [workoutSet], - ), + Invocation.method(#editSet, [workoutSet]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -459,23 +323,14 @@ class MockWorkoutPlansProvider extends _i1.Mock int? startIndex, ) => (super.noSuchMethod( - Invocation.method( - #reorderSets, - [ - sets, - startIndex, - ], - ), + Invocation.method(#reorderSets, [sets, startIndex]), returnValue: _i12.Future>.value(<_i7.Set>[]), ) as _i12.Future>); @override _i12.Future fetchComputedSettings(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #fetchComputedSettings, - [workoutSet], - ), + Invocation.method(#fetchComputedSettings, [workoutSet]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -486,31 +341,18 @@ class MockWorkoutPlansProvider extends _i1.Mock _i14.Translation? exercise, ) => (super.noSuchMethod( - Invocation.method( - #fetchSmartText, - [ - workoutSet, - exercise, - ], - ), - returnValue: _i12.Future.value(_i15.dummyValue( - this, - Invocation.method( - #fetchSmartText, - [ - workoutSet, - exercise, - ], + Invocation.method(#fetchSmartText, [workoutSet, exercise]), + returnValue: _i12.Future.value( + _i15.dummyValue( + this, + Invocation.method(#fetchSmartText, [workoutSet, exercise]), ), - )), + ), ) as _i12.Future); @override _i12.Future deleteSet(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #deleteSet, - [workoutSet], - ), + Invocation.method(#deleteSet, [workoutSet]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -518,103 +360,69 @@ class MockWorkoutPlansProvider extends _i1.Mock @override _i12.Future<_i8.Setting> addSetting(_i8.Setting? workoutSetting) => (super.noSuchMethod( - Invocation.method( - #addSetting, - [workoutSetting], - ), - returnValue: _i12.Future<_i8.Setting>.value(_FakeSetting_6( - this, - Invocation.method( - #addSetting, - [workoutSetting], + Invocation.method(#addSetting, [workoutSetting]), + returnValue: _i12.Future<_i8.Setting>.value( + _FakeSetting_6( + this, + Invocation.method(#addSetting, [workoutSetting]), ), - )), + ), ) as _i12.Future<_i8.Setting>); @override _i12.Future fetchSessionData() => (super.noSuchMethod( - Invocation.method( - #fetchSessionData, - [], - ), + Invocation.method(#fetchSessionData, []), returnValue: _i12.Future.value(), ) as _i12.Future); @override _i12.Future<_i9.WorkoutSession> addSession(_i9.WorkoutSession? session) => (super.noSuchMethod( - Invocation.method( - #addSession, - [session], - ), - returnValue: - _i12.Future<_i9.WorkoutSession>.value(_FakeWorkoutSession_7( - this, - Invocation.method( - #addSession, - [session], + Invocation.method(#addSession, [session]), + returnValue: _i12.Future<_i9.WorkoutSession>.value( + _FakeWorkoutSession_7( + this, + Invocation.method(#addSession, [session]), ), - )), + ), ) as _i12.Future<_i9.WorkoutSession>); @override _i12.Future<_i10.Log> addLog(_i10.Log? log) => (super.noSuchMethod( - Invocation.method( - #addLog, - [log], + Invocation.method(#addLog, [log]), + returnValue: _i12.Future<_i10.Log>.value( + _FakeLog_8(this, Invocation.method(#addLog, [log])), ), - returnValue: _i12.Future<_i10.Log>.value(_FakeLog_8( - this, - Invocation.method( - #addLog, - [log], - ), - )), ) as _i12.Future<_i10.Log>); @override _i12.Future deleteLog(_i10.Log? log) => (super.noSuchMethod( - Invocation.method( - #deleteLog, - [log], - ), + Invocation.method(#deleteLog, [log]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override void addListener(_i16.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i16.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/workout/weight_unit_form_widget_test.dart b/test/workout/weight_unit_form_widget_test.dart index ed68f0448..ae0fafc34 100644 --- a/test/workout/weight_unit_form_widget_test.dart +++ b/test/workout/weight_unit_form_widget_test.dart @@ -85,7 +85,8 @@ void main() { expect(find.text('plates'), findsWidgets); }); - testWidgets('Test that the correct units are set after selection', (WidgetTester tester) async { + testWidgets('Test that the correct units are set after selection', + (WidgetTester tester) async { // arrange await tester.pumpWidget(createHomeScreen()); await tester.pump(); diff --git a/test/workout/weight_unit_form_widget_test.mocks.dart b/test/workout/weight_unit_form_widget_test.mocks.dart index b43f1d2a2..ba2c7b01b 100644 --- a/test/workout/weight_unit_form_widget_test.mocks.dart +++ b/test/workout/weight_unit_form_widget_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/workout/weight_unit_form_widget_test.dart. // Do not manually edit this file. @@ -19,6 +19,7 @@ import 'package:wger/providers/body_weight.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -26,23 +27,13 @@ import 'package:wger/providers/body_weight.dart' as _i4; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWeightEntry_1 extends _i1.SmartFake implements _i3.WeightEntry { - _FakeWeightEntry_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWeightEntry_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [BodyWeightProvider]. @@ -71,129 +62,87 @@ class MockBodyWeightProvider extends _i1.Mock @override set items(List<_i3.WeightEntry>? entries) => super.noSuchMethod( - Invocation.setter( - #items, - entries, - ), + Invocation.setter(#items, entries), returnValueForMissingStub: null, ); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i3.WeightEntry findById(int? id) => (super.noSuchMethod( - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), returnValue: _FakeWeightEntry_1( this, - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), ), ) as _i3.WeightEntry); @override _i3.WeightEntry? findByDate(DateTime? date) => - (super.noSuchMethod(Invocation.method( - #findByDate, - [date], - )) as _i3.WeightEntry?); + (super.noSuchMethod(Invocation.method(#findByDate, [date])) + as _i3.WeightEntry?); @override _i5.Future> fetchAndSetEntries() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetEntries, - [], + Invocation.method(#fetchAndSetEntries, []), + returnValue: _i5.Future>.value( + <_i3.WeightEntry>[], ), - returnValue: - _i5.Future>.value(<_i3.WeightEntry>[]), ) as _i5.Future>); @override _i5.Future<_i3.WeightEntry> addEntry(_i3.WeightEntry? entry) => (super.noSuchMethod( - Invocation.method( - #addEntry, - [entry], + Invocation.method(#addEntry, [entry]), + returnValue: _i5.Future<_i3.WeightEntry>.value( + _FakeWeightEntry_1(this, Invocation.method(#addEntry, [entry])), ), - returnValue: _i5.Future<_i3.WeightEntry>.value(_FakeWeightEntry_1( - this, - Invocation.method( - #addEntry, - [entry], - ), - )), ) as _i5.Future<_i3.WeightEntry>); @override _i5.Future editEntry(_i3.WeightEntry? entry) => (super.noSuchMethod( - Invocation.method( - #editEntry, - [entry], - ), + Invocation.method(#editEntry, [entry]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future deleteEntry(int? id) => (super.noSuchMethod( - Invocation.method( - #deleteEntry, - [id], - ), + Invocation.method(#deleteEntry, [id]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override void addListener(_i6.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i6.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/workout/workout_day_form_test.dart b/test/workout/workout_day_form_test.dart index ef466062b..4e1c00c7e 100644 --- a/test/workout/workout_day_form_test.dart +++ b/test/workout/workout_day_form_test.dart @@ -56,7 +56,8 @@ void main() { ); } - testWidgets('Test the widgets on the DayFormWidget', (WidgetTester tester) async { + testWidgets('Test the widgets on the DayFormWidget', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); await tester.pumpAndSettle(); @@ -66,13 +67,15 @@ void main() { }); testWidgets('Test creating a new day', (WidgetTester tester) async { - when(mockWorkoutPlans.addDay(any, any)).thenAnswer((_) => Future.value(Day())); + when(mockWorkoutPlans.addDay(any, any)) + .thenAnswer((_) => Future.value(Day())); await tester.pumpWidget(createHomeScreen()); await tester.pumpAndSettle(); expect(find.text(''), findsOneWidget, reason: 'New day has no description'); - await tester.enterText(find.byKey(const Key('field-description')), 'Leg day!'); + await tester.enterText( + find.byKey(const Key('field-description')), 'Leg day!'); await tester.tap(find.byKey(const Key('field-checkbox-1'))); await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); @@ -83,7 +86,8 @@ void main() { //verify(mockObserver.didPop(any, any)); }); - testWidgets('Tests the localization of days - EN', (WidgetTester tester) async { + testWidgets('Tests the localization of days - EN', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); expect(find.text('Monday'), findsOneWidget); @@ -91,7 +95,8 @@ void main() { expect(find.text('Thursday'), findsOneWidget); }); - testWidgets('Tests the localization of days - DE', (WidgetTester tester) async { + testWidgets('Tests the localization of days - DE', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen(locale: 'de')); expect(find.text('Montag'), findsOneWidget); diff --git a/test/workout/workout_day_form_test.mocks.dart b/test/workout/workout_day_form_test.mocks.dart index a9dd966e7..65b0b0efb 100644 --- a/test/workout/workout_day_form_test.mocks.dart +++ b/test/workout/workout_day_form_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/workout/workout_day_form_test.dart. // Do not manually edit this file. @@ -29,6 +29,7 @@ import 'package:wger/providers/workout_plans.dart' as _i11; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -36,95 +37,50 @@ import 'package:wger/providers/workout_plans.dart' as _i11; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWeightUnit_1 extends _i1.SmartFake implements _i3.WeightUnit { - _FakeWeightUnit_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWeightUnit_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeRepetitionUnit_2 extends _i1.SmartFake implements _i4.RepetitionUnit { - _FakeRepetitionUnit_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeRepetitionUnit_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWorkoutPlan_3 extends _i1.SmartFake implements _i5.WorkoutPlan { - _FakeWorkoutPlan_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWorkoutPlan_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDay_4 extends _i1.SmartFake implements _i6.Day { - _FakeDay_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDay_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSet_5 extends _i1.SmartFake implements _i7.Set { - _FakeSet_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSet_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSetting_6 extends _i1.SmartFake implements _i8.Setting { - _FakeSetting_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSetting_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWorkoutSession_7 extends _i1.SmartFake implements _i9.WorkoutSession { - _FakeWorkoutSession_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWorkoutSession_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeLog_8 extends _i1.SmartFake implements _i10.Log { - _FakeLog_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeLog_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WorkoutPlansProvider]. @@ -182,87 +138,59 @@ class MockWorkoutPlansProvider extends _i1.Mock ) as _i4.RepetitionUnit); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override List<_i5.WorkoutPlan> getPlans() => (super.noSuchMethod( - Invocation.method( - #getPlans, - [], - ), + Invocation.method(#getPlans, []), returnValue: <_i5.WorkoutPlan>[], ) as List<_i5.WorkoutPlan>); @override _i5.WorkoutPlan findById(int? id) => (super.noSuchMethod( - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), returnValue: _FakeWorkoutPlan_3( this, - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), ), ) as _i5.WorkoutPlan); @override int findIndexById(int? id) => (super.noSuchMethod( - Invocation.method( - #findIndexById, - [id], - ), + Invocation.method(#findIndexById, [id]), returnValue: 0, ) as int); @override void setCurrentPlan(int? id) => super.noSuchMethod( - Invocation.method( - #setCurrentPlan, - [id], - ), + Invocation.method(#setCurrentPlan, [id]), returnValueForMissingStub: null, ); @override void resetCurrentPlan() => super.noSuchMethod( - Invocation.method( - #resetCurrentPlan, - [], - ), + Invocation.method(#resetCurrentPlan, []), returnValueForMissingStub: null, ); @override _i12.Future fetchAndSetAllPlansFull() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansFull, - [], - ), + Invocation.method(#fetchAndSetAllPlansFull, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future fetchAndSetAllPlansSparse() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansSparse, - [], - ), + Invocation.method(#fetchAndSetAllPlansSparse, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -270,68 +198,50 @@ class MockWorkoutPlansProvider extends _i1.Mock @override _i12.Future<_i5.WorkoutPlan> fetchAndSetPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanSparse, - [planId], - ), - returnValue: _i12.Future<_i5.WorkoutPlan>.value(_FakeWorkoutPlan_3( - this, - Invocation.method( - #fetchAndSetPlanSparse, - [planId], + Invocation.method(#fetchAndSetPlanSparse, [planId]), + returnValue: _i12.Future<_i5.WorkoutPlan>.value( + _FakeWorkoutPlan_3( + this, + Invocation.method(#fetchAndSetPlanSparse, [planId]), ), - )), + ), ) as _i12.Future<_i5.WorkoutPlan>); @override _i12.Future<_i5.WorkoutPlan> fetchAndSetWorkoutPlanFull(int? workoutId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetWorkoutPlanFull, - [workoutId], - ), - returnValue: _i12.Future<_i5.WorkoutPlan>.value(_FakeWorkoutPlan_3( - this, - Invocation.method( - #fetchAndSetWorkoutPlanFull, - [workoutId], + Invocation.method(#fetchAndSetWorkoutPlanFull, [workoutId]), + returnValue: _i12.Future<_i5.WorkoutPlan>.value( + _FakeWorkoutPlan_3( + this, + Invocation.method(#fetchAndSetWorkoutPlanFull, [workoutId]), ), - )), + ), ) as _i12.Future<_i5.WorkoutPlan>); @override _i12.Future<_i5.WorkoutPlan> addWorkout(_i5.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #addWorkout, - [workout], - ), - returnValue: _i12.Future<_i5.WorkoutPlan>.value(_FakeWorkoutPlan_3( - this, - Invocation.method( - #addWorkout, - [workout], + Invocation.method(#addWorkout, [workout]), + returnValue: _i12.Future<_i5.WorkoutPlan>.value( + _FakeWorkoutPlan_3( + this, + Invocation.method(#addWorkout, [workout]), ), - )), + ), ) as _i12.Future<_i5.WorkoutPlan>); @override _i12.Future editWorkout(_i5.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #editWorkout, - [workout], - ), + Invocation.method(#editWorkout, [workout]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future deleteWorkout(int? id) => (super.noSuchMethod( - Invocation.method( - #deleteWorkout, - [id], - ), + Invocation.method(#deleteWorkout, [id]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -342,113 +252,67 @@ class MockWorkoutPlansProvider extends _i1.Mock _i13.Exercise? base, ) => (super.noSuchMethod( - Invocation.method( - #fetchLogData, - [ - workout, - base, - ], + Invocation.method(#fetchLogData, [workout, base]), + returnValue: _i12.Future>.value( + {}, ), - returnValue: - _i12.Future>.value({}), ) as _i12.Future>); @override _i12.Future fetchAndSetRepetitionUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetRepetitionUnits, - [], - ), + Invocation.method(#fetchAndSetRepetitionUnits, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future fetchAndSetWeightUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetWeightUnits, - [], - ), + Invocation.method(#fetchAndSetWeightUnits, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future fetchAndSetUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetUnits, - [], - ), + Invocation.method(#fetchAndSetUnits, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override - _i12.Future<_i6.Day> addDay( - _i6.Day? day, - _i5.WorkoutPlan? workout, - ) => + _i12.Future<_i6.Day> addDay(_i6.Day? day, _i5.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #addDay, - [ - day, - workout, - ], + Invocation.method(#addDay, [day, workout]), + returnValue: _i12.Future<_i6.Day>.value( + _FakeDay_4(this, Invocation.method(#addDay, [day, workout])), ), - returnValue: _i12.Future<_i6.Day>.value(_FakeDay_4( - this, - Invocation.method( - #addDay, - [ - day, - workout, - ], - ), - )), ) as _i12.Future<_i6.Day>); @override _i12.Future editDay(_i6.Day? day) => (super.noSuchMethod( - Invocation.method( - #editDay, - [day], - ), + Invocation.method(#editDay, [day]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future deleteDay(_i6.Day? day) => (super.noSuchMethod( - Invocation.method( - #deleteDay, - [day], - ), + Invocation.method(#deleteDay, [day]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future<_i7.Set> addSet(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #addSet, - [workoutSet], + Invocation.method(#addSet, [workoutSet]), + returnValue: _i12.Future<_i7.Set>.value( + _FakeSet_5(this, Invocation.method(#addSet, [workoutSet])), ), - returnValue: _i12.Future<_i7.Set>.value(_FakeSet_5( - this, - Invocation.method( - #addSet, - [workoutSet], - ), - )), ) as _i12.Future<_i7.Set>); @override _i12.Future editSet(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #editSet, - [workoutSet], - ), + Invocation.method(#editSet, [workoutSet]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -459,23 +323,14 @@ class MockWorkoutPlansProvider extends _i1.Mock int? startIndex, ) => (super.noSuchMethod( - Invocation.method( - #reorderSets, - [ - sets, - startIndex, - ], - ), + Invocation.method(#reorderSets, [sets, startIndex]), returnValue: _i12.Future>.value(<_i7.Set>[]), ) as _i12.Future>); @override _i12.Future fetchComputedSettings(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #fetchComputedSettings, - [workoutSet], - ), + Invocation.method(#fetchComputedSettings, [workoutSet]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -486,31 +341,18 @@ class MockWorkoutPlansProvider extends _i1.Mock _i14.Translation? exercise, ) => (super.noSuchMethod( - Invocation.method( - #fetchSmartText, - [ - workoutSet, - exercise, - ], - ), - returnValue: _i12.Future.value(_i15.dummyValue( - this, - Invocation.method( - #fetchSmartText, - [ - workoutSet, - exercise, - ], + Invocation.method(#fetchSmartText, [workoutSet, exercise]), + returnValue: _i12.Future.value( + _i15.dummyValue( + this, + Invocation.method(#fetchSmartText, [workoutSet, exercise]), ), - )), + ), ) as _i12.Future); @override _i12.Future deleteSet(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #deleteSet, - [workoutSet], - ), + Invocation.method(#deleteSet, [workoutSet]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -518,103 +360,69 @@ class MockWorkoutPlansProvider extends _i1.Mock @override _i12.Future<_i8.Setting> addSetting(_i8.Setting? workoutSetting) => (super.noSuchMethod( - Invocation.method( - #addSetting, - [workoutSetting], - ), - returnValue: _i12.Future<_i8.Setting>.value(_FakeSetting_6( - this, - Invocation.method( - #addSetting, - [workoutSetting], + Invocation.method(#addSetting, [workoutSetting]), + returnValue: _i12.Future<_i8.Setting>.value( + _FakeSetting_6( + this, + Invocation.method(#addSetting, [workoutSetting]), ), - )), + ), ) as _i12.Future<_i8.Setting>); @override _i12.Future fetchSessionData() => (super.noSuchMethod( - Invocation.method( - #fetchSessionData, - [], - ), + Invocation.method(#fetchSessionData, []), returnValue: _i12.Future.value(), ) as _i12.Future); @override _i12.Future<_i9.WorkoutSession> addSession(_i9.WorkoutSession? session) => (super.noSuchMethod( - Invocation.method( - #addSession, - [session], - ), - returnValue: - _i12.Future<_i9.WorkoutSession>.value(_FakeWorkoutSession_7( - this, - Invocation.method( - #addSession, - [session], + Invocation.method(#addSession, [session]), + returnValue: _i12.Future<_i9.WorkoutSession>.value( + _FakeWorkoutSession_7( + this, + Invocation.method(#addSession, [session]), ), - )), + ), ) as _i12.Future<_i9.WorkoutSession>); @override _i12.Future<_i10.Log> addLog(_i10.Log? log) => (super.noSuchMethod( - Invocation.method( - #addLog, - [log], + Invocation.method(#addLog, [log]), + returnValue: _i12.Future<_i10.Log>.value( + _FakeLog_8(this, Invocation.method(#addLog, [log])), ), - returnValue: _i12.Future<_i10.Log>.value(_FakeLog_8( - this, - Invocation.method( - #addLog, - [log], - ), - )), ) as _i12.Future<_i10.Log>); @override _i12.Future deleteLog(_i10.Log? log) => (super.noSuchMethod( - Invocation.method( - #deleteLog, - [log], - ), + Invocation.method(#deleteLog, [log]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override void addListener(_i16.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i16.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/workout/workout_form_test.dart b/test/workout/workout_form_test.dart index 7528c09fa..33ec62d80 100644 --- a/test/workout/workout_form_test.dart +++ b/test/workout/workout_form_test.dart @@ -44,7 +44,8 @@ void main() { setUp(() { mockWorkoutPlans = MockWorkoutPlansProvider(); - when(mockWorkoutPlans.editWorkout(any)).thenAnswer((_) => Future.value(existingPlan)); + when(mockWorkoutPlans.editWorkout(any)) + .thenAnswer((_) => Future.value(existingPlan)); when(mockWorkoutPlans.fetchAndSetWorkoutPlanFull(any)) .thenAnswer((_) => Future.value(existingPlan)); }); @@ -67,7 +68,8 @@ void main() { ); } - testWidgets('Test the widgets on the workout form', (WidgetTester tester) async { + testWidgets('Test the widgets on the workout form', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen(existingPlan)); await tester.pumpAndSettle(); @@ -89,7 +91,8 @@ void main() { findsOneWidget, reason: 'Description of existing workout plan', ); - await tester.enterText(find.byKey(const Key('field-name')), 'New description'); + await tester.enterText( + find.byKey(const Key('field-name')), 'New description'); await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); // Correct method was called @@ -105,20 +108,24 @@ void main() { //expect(find.text(('New description')), findsOneWidget, reason: 'Workout plan detail page'); }); - testWidgets('Test creating a new workout - only name', (WidgetTester tester) async { + testWidgets('Test creating a new workout - only name', + (WidgetTester tester) async { final editWorkout = WorkoutPlan( id: 2, creationDate: newPlan.creationDate, name: 'New cool workout', ); - when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(editWorkout)); + when(mockWorkoutPlans.addWorkout(any)) + .thenAnswer((_) => Future.value(editWorkout)); await tester.pumpWidget(createHomeScreen(newPlan)); await tester.pumpAndSettle(); - expect(find.text(''), findsNWidgets(2), reason: 'New workout has no name or description'); - await tester.enterText(find.byKey(const Key('field-name')), editWorkout.name); + expect(find.text(''), findsNWidgets(2), + reason: 'New workout has no name or description'); + await tester.enterText( + find.byKey(const Key('field-name')), editWorkout.name); await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); verifyNever(mockWorkoutPlans.editWorkout(any)); @@ -126,24 +133,30 @@ void main() { // Detail page await tester.pumpAndSettle(); - expect(find.text('New cool workout'), findsOneWidget, reason: 'Workout plan detail page'); + expect(find.text('New cool workout'), findsOneWidget, + reason: 'Workout plan detail page'); }); - testWidgets('Test creating a new workout - name and description', (WidgetTester tester) async { + testWidgets('Test creating a new workout - name and description', + (WidgetTester tester) async { final editWorkout = WorkoutPlan( id: 2, creationDate: newPlan.creationDate, name: 'My workout', description: 'Get yuuuge', ); - when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(editWorkout)); + when(mockWorkoutPlans.addWorkout(any)) + .thenAnswer((_) => Future.value(editWorkout)); await tester.pumpWidget(createHomeScreen(newPlan)); await tester.pumpAndSettle(); - expect(find.text(''), findsNWidgets(2), reason: 'New workout has no name or description'); - await tester.enterText(find.byKey(const Key('field-name')), editWorkout.name); - await tester.enterText(find.byKey(const Key('field-description')), editWorkout.description); + expect(find.text(''), findsNWidgets(2), + reason: 'New workout has no name or description'); + await tester.enterText( + find.byKey(const Key('field-name')), editWorkout.name); + await tester.enterText( + find.byKey(const Key('field-description')), editWorkout.description); await tester.tap(find.byKey(const Key(SUBMIT_BUTTON_KEY_NAME))); verifyNever(mockWorkoutPlans.editWorkout(any)); @@ -151,6 +164,7 @@ void main() { // Detail page await tester.pumpAndSettle(); - expect(find.text('My workout'), findsOneWidget, reason: 'Workout plan detail page'); + expect(find.text('My workout'), findsOneWidget, + reason: 'Workout plan detail page'); }); } diff --git a/test/workout/workout_form_test.mocks.dart b/test/workout/workout_form_test.mocks.dart index 2e083a5cd..cd6d85563 100644 --- a/test/workout/workout_form_test.mocks.dart +++ b/test/workout/workout_form_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/workout/workout_form_test.dart. // Do not manually edit this file. @@ -29,6 +29,7 @@ import 'package:wger/providers/workout_plans.dart' as _i11; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -36,95 +37,50 @@ import 'package:wger/providers/workout_plans.dart' as _i11; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWeightUnit_1 extends _i1.SmartFake implements _i3.WeightUnit { - _FakeWeightUnit_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWeightUnit_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeRepetitionUnit_2 extends _i1.SmartFake implements _i4.RepetitionUnit { - _FakeRepetitionUnit_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeRepetitionUnit_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWorkoutPlan_3 extends _i1.SmartFake implements _i5.WorkoutPlan { - _FakeWorkoutPlan_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWorkoutPlan_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDay_4 extends _i1.SmartFake implements _i6.Day { - _FakeDay_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDay_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSet_5 extends _i1.SmartFake implements _i7.Set { - _FakeSet_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSet_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSetting_6 extends _i1.SmartFake implements _i8.Setting { - _FakeSetting_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSetting_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWorkoutSession_7 extends _i1.SmartFake implements _i9.WorkoutSession { - _FakeWorkoutSession_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWorkoutSession_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeLog_8 extends _i1.SmartFake implements _i10.Log { - _FakeLog_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeLog_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WorkoutPlansProvider]. @@ -182,87 +138,59 @@ class MockWorkoutPlansProvider extends _i1.Mock ) as _i4.RepetitionUnit); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override List<_i5.WorkoutPlan> getPlans() => (super.noSuchMethod( - Invocation.method( - #getPlans, - [], - ), + Invocation.method(#getPlans, []), returnValue: <_i5.WorkoutPlan>[], ) as List<_i5.WorkoutPlan>); @override _i5.WorkoutPlan findById(int? id) => (super.noSuchMethod( - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), returnValue: _FakeWorkoutPlan_3( this, - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), ), ) as _i5.WorkoutPlan); @override int findIndexById(int? id) => (super.noSuchMethod( - Invocation.method( - #findIndexById, - [id], - ), + Invocation.method(#findIndexById, [id]), returnValue: 0, ) as int); @override void setCurrentPlan(int? id) => super.noSuchMethod( - Invocation.method( - #setCurrentPlan, - [id], - ), + Invocation.method(#setCurrentPlan, [id]), returnValueForMissingStub: null, ); @override void resetCurrentPlan() => super.noSuchMethod( - Invocation.method( - #resetCurrentPlan, - [], - ), + Invocation.method(#resetCurrentPlan, []), returnValueForMissingStub: null, ); @override _i12.Future fetchAndSetAllPlansFull() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansFull, - [], - ), + Invocation.method(#fetchAndSetAllPlansFull, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future fetchAndSetAllPlansSparse() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansSparse, - [], - ), + Invocation.method(#fetchAndSetAllPlansSparse, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -270,68 +198,50 @@ class MockWorkoutPlansProvider extends _i1.Mock @override _i12.Future<_i5.WorkoutPlan> fetchAndSetPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanSparse, - [planId], - ), - returnValue: _i12.Future<_i5.WorkoutPlan>.value(_FakeWorkoutPlan_3( - this, - Invocation.method( - #fetchAndSetPlanSparse, - [planId], + Invocation.method(#fetchAndSetPlanSparse, [planId]), + returnValue: _i12.Future<_i5.WorkoutPlan>.value( + _FakeWorkoutPlan_3( + this, + Invocation.method(#fetchAndSetPlanSparse, [planId]), ), - )), + ), ) as _i12.Future<_i5.WorkoutPlan>); @override _i12.Future<_i5.WorkoutPlan> fetchAndSetWorkoutPlanFull(int? workoutId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetWorkoutPlanFull, - [workoutId], - ), - returnValue: _i12.Future<_i5.WorkoutPlan>.value(_FakeWorkoutPlan_3( - this, - Invocation.method( - #fetchAndSetWorkoutPlanFull, - [workoutId], + Invocation.method(#fetchAndSetWorkoutPlanFull, [workoutId]), + returnValue: _i12.Future<_i5.WorkoutPlan>.value( + _FakeWorkoutPlan_3( + this, + Invocation.method(#fetchAndSetWorkoutPlanFull, [workoutId]), ), - )), + ), ) as _i12.Future<_i5.WorkoutPlan>); @override _i12.Future<_i5.WorkoutPlan> addWorkout(_i5.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #addWorkout, - [workout], - ), - returnValue: _i12.Future<_i5.WorkoutPlan>.value(_FakeWorkoutPlan_3( - this, - Invocation.method( - #addWorkout, - [workout], + Invocation.method(#addWorkout, [workout]), + returnValue: _i12.Future<_i5.WorkoutPlan>.value( + _FakeWorkoutPlan_3( + this, + Invocation.method(#addWorkout, [workout]), ), - )), + ), ) as _i12.Future<_i5.WorkoutPlan>); @override _i12.Future editWorkout(_i5.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #editWorkout, - [workout], - ), + Invocation.method(#editWorkout, [workout]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future deleteWorkout(int? id) => (super.noSuchMethod( - Invocation.method( - #deleteWorkout, - [id], - ), + Invocation.method(#deleteWorkout, [id]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -342,113 +252,67 @@ class MockWorkoutPlansProvider extends _i1.Mock _i13.Exercise? base, ) => (super.noSuchMethod( - Invocation.method( - #fetchLogData, - [ - workout, - base, - ], + Invocation.method(#fetchLogData, [workout, base]), + returnValue: _i12.Future>.value( + {}, ), - returnValue: - _i12.Future>.value({}), ) as _i12.Future>); @override _i12.Future fetchAndSetRepetitionUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetRepetitionUnits, - [], - ), + Invocation.method(#fetchAndSetRepetitionUnits, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future fetchAndSetWeightUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetWeightUnits, - [], - ), + Invocation.method(#fetchAndSetWeightUnits, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future fetchAndSetUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetUnits, - [], - ), + Invocation.method(#fetchAndSetUnits, []), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override - _i12.Future<_i6.Day> addDay( - _i6.Day? day, - _i5.WorkoutPlan? workout, - ) => + _i12.Future<_i6.Day> addDay(_i6.Day? day, _i5.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #addDay, - [ - day, - workout, - ], + Invocation.method(#addDay, [day, workout]), + returnValue: _i12.Future<_i6.Day>.value( + _FakeDay_4(this, Invocation.method(#addDay, [day, workout])), ), - returnValue: _i12.Future<_i6.Day>.value(_FakeDay_4( - this, - Invocation.method( - #addDay, - [ - day, - workout, - ], - ), - )), ) as _i12.Future<_i6.Day>); @override _i12.Future editDay(_i6.Day? day) => (super.noSuchMethod( - Invocation.method( - #editDay, - [day], - ), + Invocation.method(#editDay, [day]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future deleteDay(_i6.Day? day) => (super.noSuchMethod( - Invocation.method( - #deleteDay, - [day], - ), + Invocation.method(#deleteDay, [day]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override _i12.Future<_i7.Set> addSet(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #addSet, - [workoutSet], + Invocation.method(#addSet, [workoutSet]), + returnValue: _i12.Future<_i7.Set>.value( + _FakeSet_5(this, Invocation.method(#addSet, [workoutSet])), ), - returnValue: _i12.Future<_i7.Set>.value(_FakeSet_5( - this, - Invocation.method( - #addSet, - [workoutSet], - ), - )), ) as _i12.Future<_i7.Set>); @override _i12.Future editSet(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #editSet, - [workoutSet], - ), + Invocation.method(#editSet, [workoutSet]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -459,23 +323,14 @@ class MockWorkoutPlansProvider extends _i1.Mock int? startIndex, ) => (super.noSuchMethod( - Invocation.method( - #reorderSets, - [ - sets, - startIndex, - ], - ), + Invocation.method(#reorderSets, [sets, startIndex]), returnValue: _i12.Future>.value(<_i7.Set>[]), ) as _i12.Future>); @override _i12.Future fetchComputedSettings(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #fetchComputedSettings, - [workoutSet], - ), + Invocation.method(#fetchComputedSettings, [workoutSet]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -486,31 +341,18 @@ class MockWorkoutPlansProvider extends _i1.Mock _i14.Translation? exercise, ) => (super.noSuchMethod( - Invocation.method( - #fetchSmartText, - [ - workoutSet, - exercise, - ], - ), - returnValue: _i12.Future.value(_i15.dummyValue( - this, - Invocation.method( - #fetchSmartText, - [ - workoutSet, - exercise, - ], + Invocation.method(#fetchSmartText, [workoutSet, exercise]), + returnValue: _i12.Future.value( + _i15.dummyValue( + this, + Invocation.method(#fetchSmartText, [workoutSet, exercise]), ), - )), + ), ) as _i12.Future); @override _i12.Future deleteSet(_i7.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #deleteSet, - [workoutSet], - ), + Invocation.method(#deleteSet, [workoutSet]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @@ -518,103 +360,69 @@ class MockWorkoutPlansProvider extends _i1.Mock @override _i12.Future<_i8.Setting> addSetting(_i8.Setting? workoutSetting) => (super.noSuchMethod( - Invocation.method( - #addSetting, - [workoutSetting], - ), - returnValue: _i12.Future<_i8.Setting>.value(_FakeSetting_6( - this, - Invocation.method( - #addSetting, - [workoutSetting], + Invocation.method(#addSetting, [workoutSetting]), + returnValue: _i12.Future<_i8.Setting>.value( + _FakeSetting_6( + this, + Invocation.method(#addSetting, [workoutSetting]), ), - )), + ), ) as _i12.Future<_i8.Setting>); @override _i12.Future fetchSessionData() => (super.noSuchMethod( - Invocation.method( - #fetchSessionData, - [], - ), + Invocation.method(#fetchSessionData, []), returnValue: _i12.Future.value(), ) as _i12.Future); @override _i12.Future<_i9.WorkoutSession> addSession(_i9.WorkoutSession? session) => (super.noSuchMethod( - Invocation.method( - #addSession, - [session], - ), - returnValue: - _i12.Future<_i9.WorkoutSession>.value(_FakeWorkoutSession_7( - this, - Invocation.method( - #addSession, - [session], + Invocation.method(#addSession, [session]), + returnValue: _i12.Future<_i9.WorkoutSession>.value( + _FakeWorkoutSession_7( + this, + Invocation.method(#addSession, [session]), ), - )), + ), ) as _i12.Future<_i9.WorkoutSession>); @override _i12.Future<_i10.Log> addLog(_i10.Log? log) => (super.noSuchMethod( - Invocation.method( - #addLog, - [log], + Invocation.method(#addLog, [log]), + returnValue: _i12.Future<_i10.Log>.value( + _FakeLog_8(this, Invocation.method(#addLog, [log])), ), - returnValue: _i12.Future<_i10.Log>.value(_FakeLog_8( - this, - Invocation.method( - #addLog, - [log], - ), - )), ) as _i12.Future<_i10.Log>); @override _i12.Future deleteLog(_i10.Log? log) => (super.noSuchMethod( - Invocation.method( - #deleteLog, - [log], - ), + Invocation.method(#deleteLog, [log]), returnValue: _i12.Future.value(), returnValueForMissingStub: _i12.Future.value(), ) as _i12.Future); @override void addListener(_i16.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i16.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test/workout/workout_plan_model_test.dart b/test/workout/workout_plan_model_test.dart index 57be4bb30..fb85493bc 100644 --- a/test/workout/workout_plan_model_test.dart +++ b/test/workout/workout_plan_model_test.dart @@ -27,12 +27,14 @@ void main() { final workout = getWorkout(); expect(workout.logs.length, 3); - final logExercise1 = workout.filterLogsByExerciseBase(getTestExercises()[0]); + final logExercise1 = + workout.filterLogsByExerciseBase(getTestExercises()[0]); expect(logExercise1.length, 2); expect(logExercise1[0].id, 1); expect(logExercise1[1].id, 2); - final logExercise2 = workout.filterLogsByExerciseBase(getTestExercises()[1]); + final logExercise2 = + workout.filterLogsByExerciseBase(getTestExercises()[1]); expect(logExercise2.length, 1); expect(logExercise2[0].id, 3); diff --git a/test/workout/workout_plan_screen_test.dart b/test/workout/workout_plan_screen_test.dart index b3bad988f..95a3189b5 100644 --- a/test/workout/workout_plan_screen_test.dart +++ b/test/workout/workout_plan_screen_test.dart @@ -42,7 +42,8 @@ void main() { final key = GlobalKey(); return ChangeNotifierProvider( - create: (context) => WorkoutPlansProvider(mockBaseProvider, exercisesProvider, []), + create: (context) => + WorkoutPlansProvider(mockBaseProvider, exercisesProvider, []), child: MaterialApp( locale: Locale(locale), localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -64,7 +65,8 @@ void main() { ); } - testWidgets('Test the widgets on the nutritional plan screen', (WidgetTester tester) async { + testWidgets('Test the widgets on the nutritional plan screen', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); @@ -75,7 +77,8 @@ void main() { expect(find.byType(Card), findsNWidgets(2)); }); - testWidgets('Tests the localization of times - EN', (WidgetTester tester) async { + testWidgets('Tests the localization of times - EN', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); @@ -84,7 +87,8 @@ void main() { expect(find.text('Thursday'), findsOneWidget); }); - testWidgets('Tests the localization of times - DE', (WidgetTester tester) async { + testWidgets('Tests the localization of times - DE', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen(locale: 'de')); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); diff --git a/test/workout/workout_plan_screen_test.mocks.dart b/test/workout/workout_plan_screen_test.mocks.dart index 0d3a7e096..84e1fa568 100644 --- a/test/workout/workout_plan_screen_test.mocks.dart +++ b/test/workout/workout_plan_screen_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/workout/workout_plan_screen_test.dart. // Do not manually edit this file. @@ -18,49 +18,30 @@ import 'package:wger/providers/base_provider.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -74,47 +55,33 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { @override _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_0( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) as _i2.AuthProvider); @override set auth(_i2.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -129,60 +96,39 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i5.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override _i5.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i5.Future>.value([]), ) as _i5.Future>); @override - _i5.Future> post( - Map? data, - Uri? uri, - ) => + _i5.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override @@ -191,39 +137,21 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override - _i5.Future<_i3.Response> deleteRequest( - String? url, - int? id, - ) => + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i5.Future<_i3.Response>); } diff --git a/test/workout/workout_plans_screen_test.dart b/test/workout/workout_plans_screen_test.dart index ebc8095bf..8446b2f42 100644 --- a/test/workout/workout_plans_screen_test.dart +++ b/test/workout/workout_plans_screen_test.dart @@ -54,16 +54,20 @@ void main() { host: 'localhost', path: 'api/v2/workout/', ); - when(mockBaseProvider.makeUrl('workout', query: anyNamed('query'))).thenReturn(uri); - when(mockBaseProvider.deleteRequest(any, any)).thenAnswer((_) async => http.Response('', 204)); + when(mockBaseProvider.makeUrl('workout', query: anyNamed('query'))) + .thenReturn(uri); + when(mockBaseProvider.deleteRequest(any, any)) + .thenAnswer((_) async => http.Response('', 204)); return ChangeNotifierProvider( create: (context) => WorkoutPlansProvider( mockBaseProvider, testExercisesProvider, [ - WorkoutPlan(id: 1, creationDate: DateTime(2021, 01, 01), name: 'test 1'), - WorkoutPlan(id: 2, creationDate: DateTime(2021, 02, 12), name: 'test 2'), + WorkoutPlan( + id: 1, creationDate: DateTime(2021, 01, 01), name: 'test 1'), + WorkoutPlan( + id: 2, creationDate: DateTime(2021, 02, 12), name: 'test 2'), ], ), child: MaterialApp( @@ -76,7 +80,8 @@ void main() { ); } - testWidgets('Test the widgets on the workout plans screen', (WidgetTester tester) async { + testWidgets('Test the widgets on the workout plans screen', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); //debugDumpApp(); @@ -85,7 +90,8 @@ void main() { expect(find.byType(ListTile), findsNWidgets(2)); }); - testWidgets('Test deleting an item using the Delete button', (WidgetTester tester) async { + testWidgets('Test deleting an item using the Delete button', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); await tester.tap(find.byIcon(Icons.delete).first); @@ -112,7 +118,8 @@ void main() { */ - testWidgets('Test the form on the workout plan screen', (WidgetTester tester) async { + testWidgets('Test the form on the workout plan screen', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); expect(find.byType(PlanForm), findsNothing); @@ -121,14 +128,16 @@ void main() { expect(find.byType(WorkoutForm), findsOneWidget); }); - testWidgets('Tests the localization of dates - EN', (WidgetTester tester) async { + testWidgets('Tests the localization of dates - EN', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); expect(find.text('1/1/2021'), findsOneWidget); expect(find.text('2/12/2021'), findsOneWidget); }); - testWidgets('Tests the localization of dates - DE', (WidgetTester tester) async { + testWidgets('Tests the localization of dates - DE', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen(locale: 'de')); expect(find.text('1.1.2021'), findsOneWidget); diff --git a/test/workout/workout_plans_screen_test.mocks.dart b/test/workout/workout_plans_screen_test.mocks.dart index 5e250a520..8cc7c3d89 100644 --- a/test/workout/workout_plans_screen_test.mocks.dart +++ b/test/workout/workout_plans_screen_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/workout/workout_plans_screen_test.dart. // Do not manually edit this file. @@ -18,49 +18,30 @@ import 'package:wger/providers/base_provider.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -74,47 +55,33 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { @override _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_0( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) as _i2.AuthProvider); @override set auth(_i2.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -129,60 +96,39 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i5.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override _i5.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i5.Future>.value([]), ) as _i5.Future>); @override - _i5.Future> post( - Map? data, - Uri? uri, - ) => + _i5.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override @@ -191,39 +137,21 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override - _i5.Future<_i3.Response> deleteRequest( - String? url, - int? id, - ) => + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i5.Future<_i3.Response>); } diff --git a/test/workout/workout_provider_test.dart b/test/workout/workout_provider_test.dart index d6a17e4e3..82ef0955c 100644 --- a/test/workout/workout_provider_test.dart +++ b/test/workout/workout_provider_test.dart @@ -61,7 +61,8 @@ void main() { ); // Load the entries - final provider = WorkoutPlansProvider(mockBaseProvider, exercisesProvider, []); + final provider = + WorkoutPlansProvider(mockBaseProvider, exercisesProvider, []); final plan = await provider.fetchAndSetPlanSparse(325397); final plans = provider.getPlans(); @@ -89,7 +90,8 @@ void main() { ); // Load the entries - final provider = WorkoutPlansProvider(mockBaseProvider, exercisesProvider, []); + final provider = + WorkoutPlansProvider(mockBaseProvider, exercisesProvider, []); await provider.fetchAndSetPlanSparse(325397); await provider.deleteWorkout(325397); @@ -101,13 +103,15 @@ void main() { final exercisesProvider = ExercisesProvider(mockBaseProvider); final uri = Uri.https('localhost', 'api/v2/setting-repetitionunit/'); - final tRepetitionUnits = jsonDecode(fixture('routines/repetition_units.json')); + final tRepetitionUnits = + jsonDecode(fixture('routines/repetition_units.json')); when(mockBaseProvider.makeUrl('setting-repetitionunit')).thenReturn(uri); when(mockBaseProvider.fetchPaginated(uri)) .thenAnswer((_) => Future.value(tRepetitionUnits['results'])); // Load the entries - final provider = WorkoutPlansProvider(mockBaseProvider, exercisesProvider, []); + final provider = + WorkoutPlansProvider(mockBaseProvider, exercisesProvider, []); await provider.fetchAndSetRepetitionUnits(); final repetitionUnits = provider.repetitionUnits; @@ -121,10 +125,12 @@ void main() { when(mockBaseProvider.fetchPaginated(uri)) .thenAnswer((_) => Future.value(tWeightUnits['results'])); - final ExercisesProvider testExercisesProvider = ExercisesProvider(mockBaseProvider); + final ExercisesProvider testExercisesProvider = + ExercisesProvider(mockBaseProvider); // Load the entries - final provider = WorkoutPlansProvider(mockBaseProvider, testExercisesProvider, []); + final provider = + WorkoutPlansProvider(mockBaseProvider, testExercisesProvider, []); await provider.fetchAndSetWeightUnits(); final weightUnits = provider.weightUnits; @@ -134,14 +140,17 @@ void main() { test('Test that fetch and set both type of units', () async { final weightUri = Uri.https('localhost', 'api/v2/setting-weightunit/'); - when(mockBaseProvider.makeUrl('setting-weightunit')).thenReturn(weightUri); + when(mockBaseProvider.makeUrl('setting-weightunit')) + .thenReturn(weightUri); final tWeightUnits = jsonDecode(fixture('routines/weight_units.json')); when(mockBaseProvider.fetchPaginated(weightUri)) .thenAnswer((_) => Future.value(tWeightUnits['results'])); final repUnit = Uri.https('localhost', 'api/v2/setting-repetitionunit/'); - final tRepetitionUnits = jsonDecode(fixture('routines/repetition_units.json')); - when(mockBaseProvider.makeUrl('setting-repetitionunit')).thenReturn(repUnit); + final tRepetitionUnits = + jsonDecode(fixture('routines/repetition_units.json')); + when(mockBaseProvider.makeUrl('setting-repetitionunit')) + .thenReturn(repUnit); when(mockBaseProvider.fetchPaginated(repUnit)) .thenAnswer((_) => Future.value(tRepetitionUnits['results'])); @@ -151,14 +160,16 @@ void main() { final prefs = await SharedPreferences.getInstance(); // Load the entries - final provider = WorkoutPlansProvider(mockBaseProvider, exercisesProvider, []); + final provider = + WorkoutPlansProvider(mockBaseProvider, exercisesProvider, []); await provider.fetchAndSetUnits(); final prefsJson = jsonDecode(prefs.getString(PREFS_WORKOUT_UNITS)!); expect(prefsJson['repetitionUnits'].length, 7); expect(prefsJson['weightUnit'].length, 6); expect(true, DateTime.parse(prefsJson['date']).isBefore(DateTime.now())); - expect(true, DateTime.parse(prefsJson['expiresIn']).isAfter(DateTime.now())); + expect( + true, DateTime.parse(prefsJson['expiresIn']).isAfter(DateTime.now())); }); }); } diff --git a/test/workout/workout_provider_test.mocks.dart b/test/workout/workout_provider_test.mocks.dart index cbd1cb058..acc6cf00f 100644 --- a/test/workout/workout_provider_test.mocks.dart +++ b/test/workout/workout_provider_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/workout/workout_provider_test.dart. // Do not manually edit this file. @@ -18,49 +18,30 @@ import 'package:wger/providers/base_provider.dart' as _i4; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { - _FakeAuthProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { - _FakeClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_2 extends _i1.SmartFake implements Uri { - _FakeUri_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [WgerBaseProvider]. @@ -74,47 +55,33 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { @override _i2.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_0( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), ) as _i2.AuthProvider); @override set auth(_i2.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i3.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_1( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), ) as _i3.Client); @override set client(_i3.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -129,60 +96,39 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_2( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i5.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override _i5.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i5.Future>.value([]), ) as _i5.Future>); @override - _i5.Future> post( - Map? data, - Uri? uri, - ) => + _i5.Future> post(Map? data, Uri? uri) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override @@ -191,39 +137,21 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, ), - returnValue: - _i5.Future>.value({}), ) as _i5.Future>); @override - _i5.Future<_i3.Response> deleteRequest( - String? url, - int? id, - ) => + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i5.Future<_i3.Response>.value(_FakeResponse_3( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i5.Future<_i3.Response>); } diff --git a/test/workout/workout_set_form_test.dart b/test/workout/workout_set_form_test.dart index 089618543..93c5f8ef2 100644 --- a/test/workout/workout_set_form_test.dart +++ b/test/workout/workout_set_form_test.dart @@ -69,7 +69,8 @@ void main() { ); } - testWidgets('Test the widgets on the SetFormWidget', (WidgetTester tester) async { + testWidgets('Test the widgets on the SetFormWidget', + (WidgetTester tester) async { await tester.pumpWidget(createHomeScreen()); await tester.pumpAndSettle(); @@ -81,9 +82,12 @@ void main() { }); testWidgets('Test creating a new set', (WidgetTester tester) async { - when(mockWorkoutPlans.addSet(any)).thenAnswer((_) => Future.value(Set.empty())); - when(mockWorkoutPlans.addSetting(any)).thenAnswer((_) => Future.value(Setting.empty())); - when(mockWorkoutPlans.fetchSmartText(any, any)).thenAnswer((_) => Future.value('2 x 10')); + when(mockWorkoutPlans.addSet(any)) + .thenAnswer((_) => Future.value(Set.empty())); + when(mockWorkoutPlans.addSetting(any)) + .thenAnswer((_) => Future.value(Setting.empty())); + when(mockWorkoutPlans.fetchSmartText(any, any)) + .thenAnswer((_) => Future.value('2 x 10')); when(mockExerciseProvider.searchExercise( any, languageCode: anyNamed('languageCode'), @@ -93,7 +97,8 @@ void main() { await tester.pumpWidget(createHomeScreen()); await tester.pumpAndSettle(); - await tester.enterText(find.byKey(const Key('field-typeahead')), 'exercise'); + await tester.enterText( + find.byKey(const Key('field-typeahead')), 'exercise'); await tester.pumpAndSettle(); //await tester.tap(find.byKey(const Key('exercise-1'))); diff --git a/test/workout/workout_set_form_test.mocks.dart b/test/workout/workout_set_form_test.mocks.dart index 4f0851bcc..178358210 100644 --- a/test/workout/workout_set_form_test.mocks.dart +++ b/test/workout/workout_set_form_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in wger/test/workout/workout_set_form_test.dart. // Do not manually edit this file. @@ -37,6 +37,7 @@ import 'package:wger/providers/workout_plans.dart' as _i22; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -44,197 +45,102 @@ import 'package:wger/providers/workout_plans.dart' as _i22; class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExerciseDatabase_1 extends _i1.SmartFake implements _i3.ExerciseDatabase { - _FakeExerciseDatabase_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeExerciseDatabase_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExercise_2 extends _i1.SmartFake implements _i4.Exercise { - _FakeExercise_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeExercise_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExerciseCategory_3 extends _i1.SmartFake implements _i5.ExerciseCategory { - _FakeExerciseCategory_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeExerciseCategory_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeEquipment_4 extends _i1.SmartFake implements _i6.Equipment { - _FakeEquipment_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeEquipment_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMuscle_5 extends _i1.SmartFake implements _i7.Muscle { - _FakeMuscle_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeMuscle_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeLanguage_6 extends _i1.SmartFake implements _i8.Language { - _FakeLanguage_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeLanguage_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeAuthProvider_7 extends _i1.SmartFake implements _i9.AuthProvider { - _FakeAuthProvider_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeAuthProvider_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeClient_8 extends _i1.SmartFake implements _i10.Client { - _FakeClient_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeClient_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeUri_9 extends _i1.SmartFake implements Uri { - _FakeUri_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeUri_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeResponse_10 extends _i1.SmartFake implements _i10.Response { - _FakeResponse_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeResponse_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWeightUnit_11 extends _i1.SmartFake implements _i11.WeightUnit { - _FakeWeightUnit_11( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWeightUnit_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeRepetitionUnit_12 extends _i1.SmartFake implements _i12.RepetitionUnit { - _FakeRepetitionUnit_12( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeRepetitionUnit_12(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWorkoutPlan_13 extends _i1.SmartFake implements _i13.WorkoutPlan { - _FakeWorkoutPlan_13( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWorkoutPlan_13(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDay_14 extends _i1.SmartFake implements _i14.Day { - _FakeDay_14( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDay_14(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSet_15 extends _i1.SmartFake implements _i15.Set { - _FakeSet_15( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSet_15(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSetting_16 extends _i1.SmartFake implements _i16.Setting { - _FakeSetting_16( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSetting_16(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWorkoutSession_17 extends _i1.SmartFake implements _i17.WorkoutSession { - _FakeWorkoutSession_17( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWorkoutSession_17(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeLog_18 extends _i1.SmartFake implements _i18.Log { - _FakeLog_18( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeLog_18(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [ExercisesProvider]. @@ -265,10 +171,7 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override set database(_i3.ExerciseDatabase? _database) => super.noSuchMethod( - Invocation.setter( - #database, - _database, - ), + Invocation.setter(#database, _database), returnValueForMissingStub: null, ); @@ -280,10 +183,7 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override set exercises(List<_i4.Exercise>? _exercises) => super.noSuchMethod( - Invocation.setter( - #exercises, - _exercises, - ), + Invocation.setter(#exercises, _exercises), returnValueForMissingStub: null, ); @@ -296,10 +196,7 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override set filteredExercises(List<_i4.Exercise>? newFilteredExercises) => super.noSuchMethod( - Invocation.setter( - #filteredExercises, - newFilteredExercises, - ), + Invocation.setter(#filteredExercises, newFilteredExercises), returnValueForMissingStub: null, ); @@ -336,69 +233,47 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override set languages(List<_i8.Language>? languages) => super.noSuchMethod( - Invocation.setter( - #languages, - languages, - ), + Invocation.setter(#languages, languages), returnValueForMissingStub: null, ); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override _i20.Future setFilters(_i19.Filters? newFilters) => (super.noSuchMethod( - Invocation.method( - #setFilters, - [newFilters], - ), + Invocation.method(#setFilters, [newFilters]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override void initFilters() => super.noSuchMethod( - Invocation.method( - #initFilters, - [], - ), + Invocation.method(#initFilters, []), returnValueForMissingStub: null, ); @override _i20.Future findByFilters() => (super.noSuchMethod( - Invocation.method( - #findByFilters, - [], - ), + Invocation.method(#findByFilters, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override _i4.Exercise findExerciseById(int? id) => (super.noSuchMethod( - Invocation.method( - #findExerciseById, - [id], - ), + Invocation.method(#findExerciseById, [id]), returnValue: _FakeExercise_2( this, - Invocation.method( - #findExerciseById, - [id], - ), + Invocation.method(#findExerciseById, [id]), ), ) as _i4.Exercise); @@ -418,100 +293,64 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override _i5.ExerciseCategory findCategoryById(int? id) => (super.noSuchMethod( - Invocation.method( - #findCategoryById, - [id], - ), + Invocation.method(#findCategoryById, [id]), returnValue: _FakeExerciseCategory_3( this, - Invocation.method( - #findCategoryById, - [id], - ), + Invocation.method(#findCategoryById, [id]), ), ) as _i5.ExerciseCategory); @override _i6.Equipment findEquipmentById(int? id) => (super.noSuchMethod( - Invocation.method( - #findEquipmentById, - [id], - ), + Invocation.method(#findEquipmentById, [id]), returnValue: _FakeEquipment_4( this, - Invocation.method( - #findEquipmentById, - [id], - ), + Invocation.method(#findEquipmentById, [id]), ), ) as _i6.Equipment); @override _i7.Muscle findMuscleById(int? id) => (super.noSuchMethod( - Invocation.method( - #findMuscleById, - [id], - ), + Invocation.method(#findMuscleById, [id]), returnValue: _FakeMuscle_5( this, - Invocation.method( - #findMuscleById, - [id], - ), + Invocation.method(#findMuscleById, [id]), ), ) as _i7.Muscle); @override _i8.Language findLanguageById(int? id) => (super.noSuchMethod( - Invocation.method( - #findLanguageById, - [id], - ), + Invocation.method(#findLanguageById, [id]), returnValue: _FakeLanguage_6( this, - Invocation.method( - #findLanguageById, - [id], - ), + Invocation.method(#findLanguageById, [id]), ), ) as _i8.Language); @override _i20.Future fetchAndSetCategoriesFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetCategoriesFromApi, - [], - ), + Invocation.method(#fetchAndSetCategoriesFromApi, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future fetchAndSetMusclesFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetMusclesFromApi, - [], - ), + Invocation.method(#fetchAndSetMusclesFromApi, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future fetchAndSetEquipmentsFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetEquipmentsFromApi, - [], - ), + Invocation.method(#fetchAndSetEquipmentsFromApi, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future fetchAndSetLanguagesFromApi() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetLanguagesFromApi, - [], - ), + Invocation.method(#fetchAndSetLanguagesFromApi, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -519,17 +358,13 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override _i20.Future<_i4.Exercise> fetchAndSetExercise(int? exerciseId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetExercise, - [exerciseId], - ), - returnValue: _i20.Future<_i4.Exercise>.value(_FakeExercise_2( - this, - Invocation.method( - #fetchAndSetExercise, - [exerciseId], + Invocation.method(#fetchAndSetExercise, [exerciseId]), + returnValue: _i20.Future<_i4.Exercise>.value( + _FakeExercise_2( + this, + Invocation.method(#fetchAndSetExercise, [exerciseId]), ), - )), + ), ) as _i20.Future<_i4.Exercise>); @override @@ -538,53 +373,41 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { int? exerciseId, ) => (super.noSuchMethod( - Invocation.method( - #handleUpdateExerciseFromApi, - [ - database, - exerciseId, - ], - ), - returnValue: _i20.Future<_i4.Exercise>.value(_FakeExercise_2( - this, - Invocation.method( - #handleUpdateExerciseFromApi, - [ + Invocation.method(#handleUpdateExerciseFromApi, [ + database, + exerciseId, + ]), + returnValue: _i20.Future<_i4.Exercise>.value( + _FakeExercise_2( + this, + Invocation.method(#handleUpdateExerciseFromApi, [ database, exerciseId, - ], + ]), ), - )), + ), ) as _i20.Future<_i4.Exercise>); @override _i20.Future initCacheTimesLocalPrefs({dynamic forceInit = false}) => (super.noSuchMethod( - Invocation.method( - #initCacheTimesLocalPrefs, - [], - {#forceInit: forceInit}, - ), + Invocation.method(#initCacheTimesLocalPrefs, [], { + #forceInit: forceInit, + }), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future clearAllCachesAndPrefs() => (super.noSuchMethod( - Invocation.method( - #clearAllCachesAndPrefs, - [], - ), + Invocation.method(#clearAllCachesAndPrefs, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future fetchAndSetInitialData() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetInitialData, - [], - ), + Invocation.method(#fetchAndSetInitialData, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -607,10 +430,7 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override _i20.Future updateExerciseCache(_i3.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #updateExerciseCache, - [database], - ), + Invocation.method(#updateExerciseCache, [database]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -618,10 +438,7 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override _i20.Future fetchAndSetMuscles(_i3.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetMuscles, - [database], - ), + Invocation.method(#fetchAndSetMuscles, [database]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -629,10 +446,7 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override _i20.Future fetchAndSetCategories(_i3.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetCategories, - [database], - ), + Invocation.method(#fetchAndSetCategories, [database]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -640,10 +454,7 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override _i20.Future fetchAndSetLanguages(_i3.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetLanguages, - [database], - ), + Invocation.method(#fetchAndSetLanguages, [database]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -651,10 +462,7 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override _i20.Future fetchAndSetEquipments(_i3.ExerciseDatabase? database) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetEquipments, - [database], - ), + Invocation.method(#fetchAndSetEquipments, [database]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -662,54 +470,41 @@ class MockExercisesProvider extends _i1.Mock implements _i19.ExercisesProvider { @override _i20.Future> searchExercise( String? name, { - String? languageCode = r'en', + String? languageCode = 'en', bool? searchEnglish = false, }) => (super.noSuchMethod( Invocation.method( #searchExercise, [name], - { - #languageCode: languageCode, - #searchEnglish: searchEnglish, - }, + {#languageCode: languageCode, #searchEnglish: searchEnglish}, + ), + returnValue: _i20.Future>.value( + <_i4.Exercise>[], ), - returnValue: _i20.Future>.value(<_i4.Exercise>[]), ) as _i20.Future>); @override void addListener(_i21.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i21.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } @@ -725,47 +520,33 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { @override _i9.AuthProvider get auth => (super.noSuchMethod( Invocation.getter(#auth), - returnValue: _FakeAuthProvider_7( - this, - Invocation.getter(#auth), - ), + returnValue: _FakeAuthProvider_7(this, Invocation.getter(#auth)), ) as _i9.AuthProvider); @override set auth(_i9.AuthProvider? _auth) => super.noSuchMethod( - Invocation.setter( - #auth, - _auth, - ), + Invocation.setter(#auth, _auth), returnValueForMissingStub: null, ); @override _i10.Client get client => (super.noSuchMethod( Invocation.getter(#client), - returnValue: _FakeClient_8( - this, - Invocation.getter(#client), - ), + returnValue: _FakeClient_8(this, Invocation.getter(#client)), ) as _i10.Client); @override set client(_i10.Client? _client) => super.noSuchMethod( - Invocation.setter( - #client, - _client, - ), + Invocation.setter(#client, _client), returnValueForMissingStub: null, ); @override Map getDefaultHeaders({bool? includeAuth = false}) => (super.noSuchMethod( - Invocation.method( - #getDefaultHeaders, - [], - {#includeAuth: includeAuth}, - ), + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + }), returnValue: {}, ) as Map); @@ -780,42 +561,29 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), returnValue: _FakeUri_9( this, Invocation.method( #makeUrl, [path], - { - #id: id, - #objectMethod: objectMethod, - #query: query, - }, + {#id: id, #objectMethod: objectMethod, #query: query}, ), ), ) as Uri); @override _i20.Future> fetch(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetch, - [uri], + Invocation.method(#fetch, [uri]), + returnValue: _i20.Future>.value( + {}, ), - returnValue: - _i20.Future>.value({}), ) as _i20.Future>); @override _i20.Future> fetchPaginated(Uri? uri) => (super.noSuchMethod( - Invocation.method( - #fetchPaginated, - [uri], - ), + Invocation.method(#fetchPaginated, [uri]), returnValue: _i20.Future>.value([]), ) as _i20.Future>); @@ -825,15 +593,10 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #post, - [ - data, - uri, - ], + Invocation.method(#post, [data, uri]), + returnValue: _i20.Future>.value( + {}, ), - returnValue: - _i20.Future>.value({}), ) as _i20.Future>); @override @@ -842,40 +605,22 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { Uri? uri, ) => (super.noSuchMethod( - Invocation.method( - #patch, - [ - data, - uri, - ], + Invocation.method(#patch, [data, uri]), + returnValue: _i20.Future>.value( + {}, ), - returnValue: - _i20.Future>.value({}), ) as _i20.Future>); @override - _i20.Future<_i10.Response> deleteRequest( - String? url, - int? id, - ) => + _i20.Future<_i10.Response> deleteRequest(String? url, int? id) => (super.noSuchMethod( - Invocation.method( - #deleteRequest, - [ - url, - id, - ], - ), - returnValue: _i20.Future<_i10.Response>.value(_FakeResponse_10( - this, - Invocation.method( - #deleteRequest, - [ - url, - id, - ], + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i20.Future<_i10.Response>.value( + _FakeResponse_10( + this, + Invocation.method(#deleteRequest, [url, id]), ), - )), + ), ) as _i20.Future<_i10.Response>); } @@ -934,87 +679,59 @@ class MockWorkoutPlansProvider extends _i1.Mock ) as _i12.RepetitionUnit); @override - bool get hasListeners => (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - ) as bool); + bool get hasListeners => + (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) + as bool); @override void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), + Invocation.method(#clear, []), returnValueForMissingStub: null, ); @override List<_i13.WorkoutPlan> getPlans() => (super.noSuchMethod( - Invocation.method( - #getPlans, - [], - ), + Invocation.method(#getPlans, []), returnValue: <_i13.WorkoutPlan>[], ) as List<_i13.WorkoutPlan>); @override _i13.WorkoutPlan findById(int? id) => (super.noSuchMethod( - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), returnValue: _FakeWorkoutPlan_13( this, - Invocation.method( - #findById, - [id], - ), + Invocation.method(#findById, [id]), ), ) as _i13.WorkoutPlan); @override int findIndexById(int? id) => (super.noSuchMethod( - Invocation.method( - #findIndexById, - [id], - ), + Invocation.method(#findIndexById, [id]), returnValue: 0, ) as int); @override void setCurrentPlan(int? id) => super.noSuchMethod( - Invocation.method( - #setCurrentPlan, - [id], - ), + Invocation.method(#setCurrentPlan, [id]), returnValueForMissingStub: null, ); @override void resetCurrentPlan() => super.noSuchMethod( - Invocation.method( - #resetCurrentPlan, - [], - ), + Invocation.method(#resetCurrentPlan, []), returnValueForMissingStub: null, ); @override _i20.Future fetchAndSetAllPlansFull() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansFull, - [], - ), + Invocation.method(#fetchAndSetAllPlansFull, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future fetchAndSetAllPlansSparse() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetAllPlansSparse, - [], - ), + Invocation.method(#fetchAndSetAllPlansSparse, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -1022,68 +739,50 @@ class MockWorkoutPlansProvider extends _i1.Mock @override _i20.Future<_i13.WorkoutPlan> fetchAndSetPlanSparse(int? planId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetPlanSparse, - [planId], - ), - returnValue: _i20.Future<_i13.WorkoutPlan>.value(_FakeWorkoutPlan_13( - this, - Invocation.method( - #fetchAndSetPlanSparse, - [planId], + Invocation.method(#fetchAndSetPlanSparse, [planId]), + returnValue: _i20.Future<_i13.WorkoutPlan>.value( + _FakeWorkoutPlan_13( + this, + Invocation.method(#fetchAndSetPlanSparse, [planId]), ), - )), + ), ) as _i20.Future<_i13.WorkoutPlan>); @override _i20.Future<_i13.WorkoutPlan> fetchAndSetWorkoutPlanFull(int? workoutId) => (super.noSuchMethod( - Invocation.method( - #fetchAndSetWorkoutPlanFull, - [workoutId], - ), - returnValue: _i20.Future<_i13.WorkoutPlan>.value(_FakeWorkoutPlan_13( - this, - Invocation.method( - #fetchAndSetWorkoutPlanFull, - [workoutId], + Invocation.method(#fetchAndSetWorkoutPlanFull, [workoutId]), + returnValue: _i20.Future<_i13.WorkoutPlan>.value( + _FakeWorkoutPlan_13( + this, + Invocation.method(#fetchAndSetWorkoutPlanFull, [workoutId]), ), - )), + ), ) as _i20.Future<_i13.WorkoutPlan>); @override _i20.Future<_i13.WorkoutPlan> addWorkout(_i13.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #addWorkout, - [workout], - ), - returnValue: _i20.Future<_i13.WorkoutPlan>.value(_FakeWorkoutPlan_13( - this, - Invocation.method( - #addWorkout, - [workout], + Invocation.method(#addWorkout, [workout]), + returnValue: _i20.Future<_i13.WorkoutPlan>.value( + _FakeWorkoutPlan_13( + this, + Invocation.method(#addWorkout, [workout]), ), - )), + ), ) as _i20.Future<_i13.WorkoutPlan>); @override _i20.Future editWorkout(_i13.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #editWorkout, - [workout], - ), + Invocation.method(#editWorkout, [workout]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future deleteWorkout(int? id) => (super.noSuchMethod( - Invocation.method( - #deleteWorkout, - [id], - ), + Invocation.method(#deleteWorkout, [id]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -1094,113 +793,67 @@ class MockWorkoutPlansProvider extends _i1.Mock _i4.Exercise? base, ) => (super.noSuchMethod( - Invocation.method( - #fetchLogData, - [ - workout, - base, - ], + Invocation.method(#fetchLogData, [workout, base]), + returnValue: _i20.Future>.value( + {}, ), - returnValue: - _i20.Future>.value({}), ) as _i20.Future>); @override _i20.Future fetchAndSetRepetitionUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetRepetitionUnits, - [], - ), + Invocation.method(#fetchAndSetRepetitionUnits, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future fetchAndSetWeightUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetWeightUnits, - [], - ), + Invocation.method(#fetchAndSetWeightUnits, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future fetchAndSetUnits() => (super.noSuchMethod( - Invocation.method( - #fetchAndSetUnits, - [], - ), + Invocation.method(#fetchAndSetUnits, []), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override - _i20.Future<_i14.Day> addDay( - _i14.Day? day, - _i13.WorkoutPlan? workout, - ) => + _i20.Future<_i14.Day> addDay(_i14.Day? day, _i13.WorkoutPlan? workout) => (super.noSuchMethod( - Invocation.method( - #addDay, - [ - day, - workout, - ], + Invocation.method(#addDay, [day, workout]), + returnValue: _i20.Future<_i14.Day>.value( + _FakeDay_14(this, Invocation.method(#addDay, [day, workout])), ), - returnValue: _i20.Future<_i14.Day>.value(_FakeDay_14( - this, - Invocation.method( - #addDay, - [ - day, - workout, - ], - ), - )), ) as _i20.Future<_i14.Day>); @override _i20.Future editDay(_i14.Day? day) => (super.noSuchMethod( - Invocation.method( - #editDay, - [day], - ), + Invocation.method(#editDay, [day]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future deleteDay(_i14.Day? day) => (super.noSuchMethod( - Invocation.method( - #deleteDay, - [day], - ), + Invocation.method(#deleteDay, [day]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override _i20.Future<_i15.Set> addSet(_i15.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #addSet, - [workoutSet], + Invocation.method(#addSet, [workoutSet]), + returnValue: _i20.Future<_i15.Set>.value( + _FakeSet_15(this, Invocation.method(#addSet, [workoutSet])), ), - returnValue: _i20.Future<_i15.Set>.value(_FakeSet_15( - this, - Invocation.method( - #addSet, - [workoutSet], - ), - )), ) as _i20.Future<_i15.Set>); @override _i20.Future editSet(_i15.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #editSet, - [workoutSet], - ), + Invocation.method(#editSet, [workoutSet]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -1211,23 +864,14 @@ class MockWorkoutPlansProvider extends _i1.Mock int? startIndex, ) => (super.noSuchMethod( - Invocation.method( - #reorderSets, - [ - sets, - startIndex, - ], - ), + Invocation.method(#reorderSets, [sets, startIndex]), returnValue: _i20.Future>.value(<_i15.Set>[]), ) as _i20.Future>); @override _i20.Future fetchComputedSettings(_i15.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #fetchComputedSettings, - [workoutSet], - ), + Invocation.method(#fetchComputedSettings, [workoutSet]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -1238,31 +882,18 @@ class MockWorkoutPlansProvider extends _i1.Mock _i23.Translation? exercise, ) => (super.noSuchMethod( - Invocation.method( - #fetchSmartText, - [ - workoutSet, - exercise, - ], - ), - returnValue: _i20.Future.value(_i24.dummyValue( - this, - Invocation.method( - #fetchSmartText, - [ - workoutSet, - exercise, - ], + Invocation.method(#fetchSmartText, [workoutSet, exercise]), + returnValue: _i20.Future.value( + _i24.dummyValue( + this, + Invocation.method(#fetchSmartText, [workoutSet, exercise]), ), - )), + ), ) as _i20.Future); @override _i20.Future deleteSet(_i15.Set? workoutSet) => (super.noSuchMethod( - Invocation.method( - #deleteSet, - [workoutSet], - ), + Invocation.method(#deleteSet, [workoutSet]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @@ -1270,103 +901,69 @@ class MockWorkoutPlansProvider extends _i1.Mock @override _i20.Future<_i16.Setting> addSetting(_i16.Setting? workoutSetting) => (super.noSuchMethod( - Invocation.method( - #addSetting, - [workoutSetting], - ), - returnValue: _i20.Future<_i16.Setting>.value(_FakeSetting_16( - this, - Invocation.method( - #addSetting, - [workoutSetting], + Invocation.method(#addSetting, [workoutSetting]), + returnValue: _i20.Future<_i16.Setting>.value( + _FakeSetting_16( + this, + Invocation.method(#addSetting, [workoutSetting]), ), - )), + ), ) as _i20.Future<_i16.Setting>); @override _i20.Future fetchSessionData() => (super.noSuchMethod( - Invocation.method( - #fetchSessionData, - [], - ), + Invocation.method(#fetchSessionData, []), returnValue: _i20.Future.value(), ) as _i20.Future); @override _i20.Future<_i17.WorkoutSession> addSession(_i17.WorkoutSession? session) => (super.noSuchMethod( - Invocation.method( - #addSession, - [session], - ), - returnValue: - _i20.Future<_i17.WorkoutSession>.value(_FakeWorkoutSession_17( - this, - Invocation.method( - #addSession, - [session], + Invocation.method(#addSession, [session]), + returnValue: _i20.Future<_i17.WorkoutSession>.value( + _FakeWorkoutSession_17( + this, + Invocation.method(#addSession, [session]), ), - )), + ), ) as _i20.Future<_i17.WorkoutSession>); @override _i20.Future<_i18.Log> addLog(_i18.Log? log) => (super.noSuchMethod( - Invocation.method( - #addLog, - [log], + Invocation.method(#addLog, [log]), + returnValue: _i20.Future<_i18.Log>.value( + _FakeLog_18(this, Invocation.method(#addLog, [log])), ), - returnValue: _i20.Future<_i18.Log>.value(_FakeLog_18( - this, - Invocation.method( - #addLog, - [log], - ), - )), ) as _i20.Future<_i18.Log>); @override _i20.Future deleteLog(_i18.Log? log) => (super.noSuchMethod( - Invocation.method( - #deleteLog, - [log], - ), + Invocation.method(#deleteLog, [log]), returnValue: _i20.Future.value(), returnValueForMissingStub: _i20.Future.value(), ) as _i20.Future); @override void addListener(_i21.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #addListener, - [listener], - ), + Invocation.method(#addListener, [listener]), returnValueForMissingStub: null, ); @override void removeListener(_i21.VoidCallback? listener) => super.noSuchMethod( - Invocation.method( - #removeListener, - [listener], - ), + Invocation.method(#removeListener, [listener]), returnValueForMissingStub: null, ); @override void dispose() => super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValueForMissingStub: null, ); @override void notifyListeners() => super.noSuchMethod( - Invocation.method( - #notifyListeners, - [], - ), + Invocation.method(#notifyListeners, []), returnValueForMissingStub: null, ); } diff --git a/test_data/body_weight.dart b/test_data/body_weight.dart index b9f892007..6f43815c3 100644 --- a/test_data/body_weight.dart +++ b/test_data/body_weight.dart @@ -18,8 +18,10 @@ import 'package:wger/models/body_weight/weight_entry.dart'; -final testWeightEntry1 = WeightEntry(id: 1, weight: 80, date: DateTime(2021, 01, 01)); -final testWeightEntry2 = WeightEntry(id: 2, weight: 81, date: DateTime(2021, 01, 10)); +final testWeightEntry1 = + WeightEntry(id: 1, weight: 80, date: DateTime(2021, 01, 01)); +final testWeightEntry2 = + WeightEntry(id: 2, weight: 81, date: DateTime(2021, 01, 10)); List getWeightEntries() { return [testWeightEntry1, testWeightEntry2]; diff --git a/test_data/exercises.dart b/test_data/exercises.dart index f9ea5789b..f7ed2c250 100644 --- a/test_data/exercises.dart +++ b/test_data/exercises.dart @@ -32,9 +32,12 @@ const tLanguage4 = Language(id: 12, shortName: 'es', fullName: 'Español'); const tLanguage5 = Language(id: 13, shortName: 'it', fullName: 'Italiano'); const testLanguages = [tLanguage1, tLanguage2, tLanguage3]; -const tMuscle1 = Muscle(id: 1, name: 'Flutterus maximus', nameEn: 'Glutes', isFront: true); -const tMuscle2 = Muscle(id: 2, name: 'Biceps brachii', nameEn: 'Biceps', isFront: true); -const tMuscle3 = Muscle(id: 3, name: 'Gluteus maximus', nameEn: 'Glutes', isFront: false); +const tMuscle1 = + Muscle(id: 1, name: 'Flutterus maximus', nameEn: 'Glutes', isFront: true); +const tMuscle2 = + Muscle(id: 2, name: 'Biceps brachii', nameEn: 'Biceps', isFront: true); +const tMuscle3 = + Muscle(id: 3, name: 'Gluteus maximus', nameEn: 'Glutes', isFront: false); const testMuscles = [tMuscle1, tMuscle2, tMuscle3]; const tCategory1 = ExerciseCategory(id: 1, name: 'Arms'); @@ -42,7 +45,13 @@ const tCategory2 = ExerciseCategory(id: 2, name: 'Legs'); const tCategory3 = ExerciseCategory(id: 3, name: 'Abs'); const tCategory4 = ExerciseCategory(id: 4, name: 'Shoulders'); const tCategory5 = ExerciseCategory(id: 5, name: 'Calves'); -const testCategories = [tCategory1, tCategory2, tCategory3, tCategory4, tCategory5]; +const testCategories = [ + tCategory1, + tCategory2, + tCategory3, + tCategory4, + tCategory5 +]; const tEquipment1 = Equipment(id: 1, name: 'Bench'); const tEquipment2 = Equipment(id: 2, name: 'Dumbbell'); @@ -121,7 +130,8 @@ final benchPressDe = Translation( name: 'Bankdrücken', description: 'add clever text', exerciseId: benchPress.id, - language: tLanguage1, + languageId: tLanguage1.id, + languageObj: tLanguage1, ); final benchPressEn = Translation( id: 7, @@ -130,7 +140,8 @@ final benchPressEn = Translation( name: 'Bench press', description: 'add clever text', exerciseId: benchPress.id, - language: tLanguage1, + languageId: tLanguage1.id, + languageObj: tLanguage1, ); final deadLiftEn = Translation( @@ -140,68 +151,73 @@ final deadLiftEn = Translation( name: 'Dead Lift', description: 'Lorem ipsum etc', exerciseId: crunches.id, - language: tLanguage2, + languageId: tLanguage2.id, + languageObj: tLanguage2, ); final crunchesFr = Translation( - id: 3, - uuid: 'd83f572d-add5-48dc-89cf-75f6770284f1', - created: DateTime(2021, 4, 1), - name: 'Crunches', - description: 'The man in black fled across the desert, and the gunslinger followed', - exerciseId: deadLift.id, - language: tLanguage3, -); + id: 3, + uuid: 'd83f572d-add5-48dc-89cf-75f6770284f1', + created: DateTime(2021, 4, 1), + name: 'Crunches', + description: + 'The man in black fled across the desert, and the gunslinger followed', + exerciseId: deadLift.id, + languageId: tLanguage3.id, + languageObj: tLanguage3); final crunchesDe = Translation( - id: 4, - uuid: 'a3e96c1d-b35f-4b0e-9cf4-ca37666cf521', - created: DateTime(2021, 4, 1), - name: 'Crunches', - description: 'The story so far: in the beginning, the universe was created', - exerciseId: deadLift.id, - language: tLanguage1, -); + id: 4, + uuid: 'a3e96c1d-b35f-4b0e-9cf4-ca37666cf521', + created: DateTime(2021, 4, 1), + name: 'Crunches', + description: 'The story so far: in the beginning, the universe was created', + exerciseId: deadLift.id, + languageId: tLanguage1.id, + languageObj: tLanguage1); final crunchesEn = Translation( - id: 5, - uuid: '8c49a816-2247-4116-94bb-b5c0ce09c609', - created: DateTime(2021, 4, 1), - name: 'test exercise 5', - description: 'I am an invisible man', - exerciseId: deadLift.id, - language: tLanguage2, -); + id: 5, + uuid: '8c49a816-2247-4116-94bb-b5c0ce09c609', + created: DateTime(2021, 4, 1), + name: 'test exercise 5', + description: 'I am an invisible man', + exerciseId: deadLift.id, + languageId: tLanguage2.id, + languageObj: tLanguage2); final curlsEn = Translation( - id: 6, - uuid: '259a637e-957f-4fe1-b61b-f56e3793ebcd', - created: DateTime(2021, 4, 1), - name: 'Curls', - description: 'It was a bright cold day in April, and the clocks were striking thirteen', - exerciseId: curls.id, - language: tLanguage2, -); + id: 6, + uuid: '259a637e-957f-4fe1-b61b-f56e3793ebcd', + created: DateTime(2021, 4, 1), + name: 'Curls', + description: + 'It was a bright cold day in April, and the clocks were striking thirteen', + exerciseId: curls.id, + languageId: tLanguage2.id, + languageObj: tLanguage2); final squatsEn = Translation( - id: 8, - uuid: '259a637e-957f-4fe1-b61b-f56e3793ebcd', - created: DateTime(2021, 4, 1), - name: 'Squats', - description: 'It was a bright cold day in April, and the clocks were striking thirteen', - exerciseId: curls.id, - language: tLanguage2, -); + id: 8, + uuid: '259a637e-957f-4fe1-b61b-f56e3793ebcd', + created: DateTime(2021, 4, 1), + name: 'Squats', + description: + 'It was a bright cold day in April, and the clocks were striking thirteen', + exerciseId: curls.id, + languageId: tLanguage2.id, + languageObj: tLanguage2); final sideRaisesEn = Translation( - id: 9, - uuid: '6bf89ad0-5a43-4e98-91d3-a8c6886c9712', - created: DateTime(2022, 11, 1), - name: 'Side raises', - description: 'It was a bright cold day in April, and the clocks were striking thirteen', - exerciseId: curls.id, - language: tLanguage2, -); + id: 9, + uuid: '6bf89ad0-5a43-4e98-91d3-a8c6886c9712', + created: DateTime(2022, 11, 1), + name: 'Side raises', + description: + 'It was a bright cold day in April, and the clocks were striking thirteen', + exerciseId: curls.id, + languageId: tLanguage2.id, + languageObj: tLanguage2); List getTestExercises() { benchPress.translations = [benchPressEn, benchPressDe]; diff --git a/test_data/measurements.dart b/test_data/measurements.dart index 87c524ebd..0e8c70b52 100644 --- a/test_data/measurements.dart +++ b/test_data/measurements.dart @@ -19,16 +19,23 @@ import 'package:wger/models/measurements/measurement_category.dart'; import 'package:wger/models/measurements/measurement_entry.dart'; -final e1 = MeasurementEntry(id: 1, category: 1, date: DateTime(2022, 9, 10), value: 30, notes: ''); -final e2 = MeasurementEntry(id: 2, category: 1, date: DateTime(2022, 10, 5), value: 25, notes: ''); -final e3 = MeasurementEntry(id: 3, category: 1, date: DateTime(2022, 10, 10), value: 17, notes: ''); -final e4 = MeasurementEntry(id: 4, category: 1, date: DateTime(2022, 11, 1), value: 17, notes: ''); -final e5 = MeasurementEntry(id: 5, category: 1, date: DateTime(2022, 11, 10), value: 20, notes: ''); -final e6 = MeasurementEntry(id: 6, category: 1, date: DateTime(2022, 11, 15), value: 23, notes: ''); +final e1 = MeasurementEntry( + id: 1, category: 1, date: DateTime(2022, 9, 10), value: 30, notes: ''); +final e2 = MeasurementEntry( + id: 2, category: 1, date: DateTime(2022, 10, 5), value: 25, notes: ''); +final e3 = MeasurementEntry( + id: 3, category: 1, date: DateTime(2022, 10, 10), value: 17, notes: ''); +final e4 = MeasurementEntry( + id: 4, category: 1, date: DateTime(2022, 11, 1), value: 17, notes: ''); +final e5 = MeasurementEntry( + id: 5, category: 1, date: DateTime(2022, 11, 10), value: 20, notes: ''); +final e6 = MeasurementEntry( + id: 6, category: 1, date: DateTime(2022, 11, 15), value: 23, notes: ''); List getMeasurementCategories() { final entries = [e1, e2, e3, e4, e5, e6]; - final category = MeasurementCategory(id: 1, name: 'Body fat', unit: '%', entries: entries); + final category = + MeasurementCategory(id: 1, name: 'Body fat', unit: '%', entries: entries); return [category]; } diff --git a/test_data/nutritional_plans.dart b/test_data/nutritional_plans.dart index 1b3a42cc6..1f56f2eb4 100644 --- a/test_data/nutritional_plans.dart +++ b/test_data/nutritional_plans.dart @@ -179,9 +179,12 @@ NutritionalPlan getNutritionalPlan() { plan.meals = [meal1, meal2]; // Add logs - plan.diaryEntries.add(Log.fromMealItem(mealItem1, 1, 1, DateTime(2021, 6, 1))); - plan.diaryEntries.add(Log.fromMealItem(mealItem2, 1, 1, DateTime(2021, 6, 1))); - plan.diaryEntries.add(Log.fromMealItem(mealItem3, 1, 1, DateTime(2021, 6, 10))); + plan.diaryEntries + .add(Log.fromMealItem(mealItem1, 1, 1, DateTime(2021, 6, 1))); + plan.diaryEntries + .add(Log.fromMealItem(mealItem2, 1, 1, DateTime(2021, 6, 1))); + plan.diaryEntries + .add(Log.fromMealItem(mealItem3, 1, 1, DateTime(2021, 6, 10))); return plan; } diff --git a/test_data/screenshots_exercises.dart b/test_data/screenshots_exercises.dart index a801bd595..b107578ec 100644 --- a/test_data/screenshots_exercises.dart +++ b/test_data/screenshots_exercises.dart @@ -32,69 +32,69 @@ const tLanguage6 = Language(id: 6, shortName: 'nl', fullName: 'Nederlands'); const tLanguage7 = Language(id: 7, shortName: 'pt', fullName: 'Português'); final squatsPT = Translation( - id: 1598, - uuid: '620fef1e-19c5-4bfe-bc8d-9dac6764c386', - created: DateTime(2021, 1, 15), - name: 'Agachamento de impulso', - description: - '''

Posição inicial:

Comece na posição de prancha alta:costas, braços e pernas retos e as mãos afastadas alinhadas aos ombros.

Passos:

  1. Pule jogando seus pés para frente entre os braços, mantendo as costas reta.
  2. Mantendo suas mãos no chão, retorne suas pernas para a posição de prancha altas.
  3. Repita.
''', - exerciseId: 616, - language: tLanguage7, -); + id: 1598, + uuid: '620fef1e-19c5-4bfe-bc8d-9dac6764c386', + created: DateTime(2021, 1, 15), + name: 'Agachamento de impulso', + description: + '''

Posição inicial:

Comece na posição de prancha alta:costas, braços e pernas retos e as mãos afastadas alinhadas aos ombros.

Passos:

  1. Pule jogando seus pés para frente entre os braços, mantendo as costas reta.
  2. Mantendo suas mãos no chão, retorne suas pernas para a posição de prancha altas.
  3. Repita.
''', + exerciseId: 616, + languageId: tLanguage7.id, + languageObj: tLanguage7); final squatsNL = Translation( - id: 1599, - uuid: 'ad8d8323-6f73-4215-9510-4d0f0c8d09d1', - created: DateTime(2021, 1, 15), - name: 'Hurkstoten', - description: - '''

Startpositie:

Begin in hoge plankpositie:rug, armen en benen recht en handen op schouderbreedte uit elkaar.

Stap:

  1. Spring met je voeten naar voren tussen je armen en houd je rug plat.
  2. Houd je handen op de vloer, spring je benen terug in hoge plank positie.
  3. Herhalen.
''', - exerciseId: 616, - language: tLanguage6, -); + id: 1599, + uuid: 'ad8d8323-6f73-4215-9510-4d0f0c8d09d1', + created: DateTime(2021, 1, 15), + name: 'Hurkstoten', + description: + '''

Startpositie:

Begin in hoge plankpositie:rug, armen en benen recht en handen op schouderbreedte uit elkaar.

Stap:

  1. Spring met je voeten naar voren tussen je armen en houd je rug plat.
  2. Houd je handen op de vloer, spring je benen terug in hoge plank positie.
  3. Herhalen.
''', + exerciseId: 616, + languageId: tLanguage6.id, + languageObj: tLanguage6); final squatsID = Translation( - id: 1600, - uuid: '74df4b83-df24-4d87-9abd-18c74e56ebff', - created: DateTime(2021, 1, 15), - name: 'Jongkok menyodorkan', - description: - '''

Posisi awal:

Mulailah dengan posisi papan tinggi:punggung, lengan, dan kaki lurus dan tangan selebar bahu.

Langkah:

  1. Lompati kaki Anda ke depan di antara kedua lengan, jaga punggung tetap rata.
  2. Menjaga tangan Anda di lantai, melompat kaki Anda kembali ke posisi papan tinggi.
  3. Ulangi.
''', - exerciseId: 616, - language: tLanguage23, -); + id: 1600, + uuid: '74df4b83-df24-4d87-9abd-18c74e56ebff', + created: DateTime(2021, 1, 15), + name: 'Jongkok menyodorkan', + description: + '''

Posisi awal:

Mulailah dengan posisi papan tinggi:punggung, lengan, dan kaki lurus dan tangan selebar bahu.

Langkah:

  1. Lompati kaki Anda ke depan di antara kedua lengan, jaga punggung tetap rata.
  2. Menjaga tangan Anda di lantai, melompat kaki Anda kembali ke posisi papan tinggi.
  3. Ulangi.
''', + exerciseId: 616, + languageId: tLanguage23.id, + languageObj: tLanguage23); final squatsDE = Translation( - id: 1601, - uuid: '707e4acd-2068-416a-9c1d-c1c3c09fdafd', - created: DateTime(2021, 1, 15), - name: 'Kniebeugen', - description: - '''

Ausgangsposition:

Beginne in der hohen Plank-Position:Rücken, Arme und Beine sind gestreckt, die Hände sind schulterbreit auseinander.

Schritte:

  1. Springe mit den Füßen zwischen den Armen nach vorne und halte den Rücken flach.
  2. Lasse die Hände auf dem Boden und springe mit den Beinen zurück in die hohe Plank-Position.
  3. Wiederhole die Übung.
''', - exerciseId: 616, - language: tLanguage1, -); + id: 1601, + uuid: '707e4acd-2068-416a-9c1d-c1c3c09fdafd', + created: DateTime(2021, 1, 15), + name: 'Kniebeugen', + description: + '''

Ausgangsposition:

Beginne in der hohen Plank-Position:Rücken, Arme und Beine sind gestreckt, die Hände sind schulterbreit auseinander.

Schritte:

  1. Springe mit den Füßen zwischen den Armen nach vorne und halte den Rücken flach.
  2. Lasse die Hände auf dem Boden und springe mit den Beinen zurück in die hohe Plank-Position.
  3. Wiederhole die Übung.
''', + exerciseId: 616, + languageId: tLanguage1.id, + languageObj: tLanguage1); final squatsFR = Translation( - id: 1602, - uuid: 'de068084-3779-4946-9ace-80efa23b7f89', - created: DateTime(2021, 1, 15), - name: 'Poussées de squat', - description: '''''', - exerciseId: 616, - language: tLanguage12, -); + id: 1602, + uuid: 'de068084-3779-4946-9ace-80efa23b7f89', + created: DateTime(2021, 1, 15), + name: 'Poussées de squat', + description: '''''', + exerciseId: 616, + languageId: tLanguage12.id, + languageObj: tLanguage12); final squatsIT = Translation( - id: 1603, - uuid: 'ab2193fb-0c9c-46a3-9b6b-fada20eb5eaa', - created: DateTime(2021, 1, 15), - name: 'Spinte squat', - description: - '''

Posizione di partenza:

Iniziare in posizione di plank alto:schiena, braccia e gambe dritte e mani alla larghezza delle spalle.

Passi:

  1. Saltare i piedi in avanti tra le braccia, mantenendo la schiena piatta.
  2. Tenendo le mani sul pavimento, saltare le gambe indietro in posizione di plank alto.
  3. Ripetere.
''', - exerciseId: 616, - language: tLanguage13, -); + id: 1603, + uuid: 'ab2193fb-0c9c-46a3-9b6b-fada20eb5eaa', + created: DateTime(2021, 1, 15), + name: 'Spinte squat', + description: + '''

Posizione di partenza:

Iniziare in posizione di plank alto:schiena, braccia e gambe dritte e mani alla larghezza delle spalle.

Passi:

  1. Saltare i piedi in avanti tra le braccia, mantenendo la schiena piatta.
  2. Tenendo le mani sul pavimento, saltare le gambe indietro in posizione di plank alto.
  3. Ripetere.
''', + exerciseId: 616, + languageId: tLanguage13.id, + languageObj: tLanguage13); final squatsEN = Translation( id: 795, @@ -104,41 +104,42 @@ final squatsEN = Translation( description: '''The burpee, or squat thrust, is a full body exercise used in strength training and as an aerobic exercise. The basic movement is performed in four steps and known as a four-count burpee: Begin in a standing position. Move into a squat position with your hands on the ground. (count 1) Kick your feet back into a plank position, while keeping your arms extended. (count 2) Immediately return your feet into squat position. (count 3) Stand up from the squat position (count 4)''', exerciseId: 616, - language: tLanguage2, + languageObj: tLanguage2, + languageId: tLanguage2.id, ); final squatsEL = Translation( - id: 1604, - uuid: 'fd6ac5d0-08da-4dc7-87b7-af316504dcda', - created: DateTime(2021, 1, 15), - name: 'Ωθήσεις βαθέος καθίσματος', - description: - '''

Θέση εκκίνησης:

Εκκίνηση σε θέση υψηλής σανίδας:πλάτη, χέρια και πόδια είναι ίσια, και τα χέρια βρίσκονται στο πλάτος των ώμων.

Βήματα:

  1. Πηδήξτε με τα πόδια προς τα εμπρός ανάμεσα στα χέρια, κρατώντας την πλάτη επίπεδη.
  2. Διατηρώντας τα χέρια στο πάτωμα, πηδήξτε με τα πόδια σας πίσω σε θέση υψηλής σανίδας.
  3. Επαναλάβετε.
''', - exerciseId: 616, - language: tLanguage8, -); + id: 1604, + uuid: 'fd6ac5d0-08da-4dc7-87b7-af316504dcda', + created: DateTime(2021, 1, 15), + name: 'Ωθήσεις βαθέος καθίσματος', + description: + '''

Θέση εκκίνησης:

Εκκίνηση σε θέση υψηλής σανίδας:πλάτη, χέρια και πόδια είναι ίσια, και τα χέρια βρίσκονται στο πλάτος των ώμων.

Βήματα:

  1. Πηδήξτε με τα πόδια προς τα εμπρός ανάμεσα στα χέρια, κρατώντας την πλάτη επίπεδη.
  2. Διατηρώντας τα χέρια στο πάτωμα, πηδήξτε με τα πόδια σας πίσω σε θέση υψηλής σανίδας.
  3. Επαναλάβετε.
''', + exerciseId: 616, + languageId: tLanguage8.id, + languageObj: tLanguage8); final squatsAR = Translation( - id: 1605, - uuid: 'ae573182-e32f-434f-829d-536947e966fb', - created: DateTime(2021, 1, 15), - name: 'دفعات القرفصاء', - description: - '''

وضع البداية:

ابدأ في وضع اللوح الخشبي المرتفع:الظهر والذراعين والساقين مستقيمين واليدين متباعدتين بعرض الكتفين.

الخطوات:

  1. اقفز قدميك للأمام بين ذراعيك ، مع الحفاظ على ظهرك مسطحًا.
  2. إبقاء يديك على الأرض ، واقفز رجليك إلى الوراء في وضع اللوح الخشبي العالي.
  3. كرر.
''', - exerciseId: 616, - language: tLanguage17, -); + id: 1605, + uuid: 'ae573182-e32f-434f-829d-536947e966fb', + created: DateTime(2021, 1, 15), + name: 'دفعات القرفصاء', + description: + '''

وضع البداية:

ابدأ في وضع اللوح الخشبي المرتفع:الظهر والذراعين والساقين مستقيمين واليدين متباعدتين بعرض الكتفين.

الخطوات:

  1. اقفز قدميك للأمام بين ذراعيك ، مع الحفاظ على ظهرك مسطحًا.
  2. إبقاء يديك على الأرض ، واقفز رجليك إلى الوراء في وضع اللوح الخشبي العالي.
  3. كرر.
''', + exerciseId: 616, + languageId: tLanguage17.id, + languageObj: tLanguage17); final squatsZH = Translation( - id: 1606, - uuid: '3c39e44c-4832-4937-bcad-ff6678c02203', - created: DateTime(2021, 1, 15), - name: '俯卧撑腿屈伸', - description: - '''

起始姿势:以高位平板支撑姿势开始:背部、手臂和腿均伸直,双手分开与肩同宽。

步骤:

  1. 双脚向双臂的方向向前跳,保持背部平直。
  2. 双手撑地,双腿跳回高位平板支撑位置。
  3. 重复。
''', - exerciseId: 616, - language: tLanguage24, -); + id: 1606, + uuid: '3c39e44c-4832-4937-bcad-ff6678c02203', + created: DateTime(2021, 1, 15), + name: '俯卧撑腿屈伸', + description: + '''

起始姿势:以高位平板支撑姿势开始:背部、手臂和腿均伸直,双手分开与肩同宽。

步骤:

  1. 双脚向双臂的方向向前跳,保持背部平直。
  2. 双手撑地,双腿跳回高位平板支撑位置。
  3. 重复。
''', + exerciseId: 616, + languageId: tLanguage24.id, + languageObj: tLanguage24); final squatsTranslations = [ squatsPT, @@ -154,11 +155,11 @@ final squatsTranslations = [ ]; final benchPressDE = Translation( - id: 15, - uuid: '198dcb2e-e35f-4b69-ae8b-e1124d438eae', - created: DateTime(2021, 1, 15), - name: 'Bankdrücken LH', - description: ''' + id: 15, + uuid: '198dcb2e-e35f-4b69-ae8b-e1124d438eae', + created: DateTime(2021, 1, 15), + name: 'Bankdrücken LH', + description: '''

Lege dich auf die Bank, die Stange direkt über die Augen, die Knie etwas angewinkelt und die Füße fest auf dem Boden. Greife die Stange breit und lasse sie langsam und kontrolliert runter, dabei sollte die Stange kurz auf Brustwarzenhöhe den Körper berühren. Dann das Gewicht wieder hochdrücken bis die Arme durchgestreckt sind.

Bei hohem Gewicht, empfielt sich natürlich einen Spotter zu haben, der einen hilft falls man die Stange nicht alleine hochdrücken kann.

Mit der Breite des Griffs kann außerdem kontrolliert werden, welcher Bereich der Brust stärker belastet wird:

@@ -166,16 +167,16 @@ final benchPressDE = Translation(
  • breiter Griff: äußere Brustmuskeln
  • enger Griff: innere Brustmuskeln und Trizeps
  • ''', - exerciseId: 73, - language: tLanguage1, -); + exerciseId: 73, + languageId: tLanguage1.id, + languageObj: tLanguage1); final benchPressEN = Translation( - id: 192, - uuid: '5da6340b-22ec-4c1b-a443-eef2f59f92f0', - created: DateTime(2021, 1, 15), - name: 'Bench Press', - description: ''' + id: 192, + uuid: '5da6340b-22ec-4c1b-a443-eef2f59f92f0', + created: DateTime(2021, 1, 15), + name: 'Bench Press', + description: '''

    Lay down on a bench, the bar should be directly above your eyes, the knees are somewhat angled and the feet are firmly on the floor. Concentrate, breath deeply and grab the bar more than shoulder wide. Bring it slowly down till it briefly touches your chest at the height of your nipples. Push the bar up.

    If you train with a high weight it is advisable to have a spotter that can help you up if you can't lift the weight on your own.

    With the width of the grip you can also control which part of the chest is trained more:

    @@ -183,193 +184,194 @@ final benchPressEN = Translation(
  • wide grip: outer chest muscles
  • narrow grip: inner chest muscles and triceps
  • ''', - exerciseId: 73, - language: tLanguage2, -); + exerciseId: 73, + languageId: tLanguage2.id, + languageObj: tLanguage2); final benchPressIT = Translation( - id: 1218, - uuid: '92fd2bf0-9cf8-40fc-8a69-e5e16136327d', - created: DateTime(2021, 1, 15), - name: 'Distensione Panca Piana con Bilanciere', - description: '''Distensione Panca Piana con BilanciereDistensione Panca Piana con Bilanciere''', - exerciseId: 73, - language: tLanguage13, -); + id: 1218, + uuid: '92fd2bf0-9cf8-40fc-8a69-e5e16136327d', + created: DateTime(2021, 1, 15), + name: 'Distensione Panca Piana con Bilanciere', + description: + '''Distensione Panca Piana con BilanciereDistensione Panca Piana con Bilanciere''', + exerciseId: 73, + languageId: tLanguage13.id, + languageObj: tLanguage13); final benchPressTranslations = [benchPressDE, benchPressEN, benchPressIT]; final deadLiftEN = Translation( - id: 105, - uuid: '22cca8fc-cfaf-4941-b0f7-faf9f2937c52', - created: DateTime(2021, 1, 15), - name: 'Deadlifts', - description: ''' + id: 105, + uuid: '22cca8fc-cfaf-4941-b0f7-faf9f2937c52', + created: DateTime(2021, 1, 15), + name: 'Deadlifts', + description: '''

    Stand firmly, with your feet slightly more than shoulder wide apart. Stand directly behind the bar where it should barely touch your shin, your feet pointing a bit out. Bend down with a straight back, the knees also pointing somewhat out. Grab the bar with a shoulder wide grip, one underhand, one reverse grip.

    Pull the weight up. At the highest point make a slight hollow back and pull the bar back. Hold 1 or 2 seconds that position. Go down, making sure the back is not bent. Once down you can either go back again as soon as the weights touch the floor, or make a pause, depending on the weight.

    ''', - exerciseId: 184, - language: tLanguage2, -); + exerciseId: 184, + languageId: tLanguage2.id, + languageObj: tLanguage2); final deadLiftDE = Translation( - id: 9, - uuid: '521a5e4f-6f35-43e5-9d1c-6e75c4956e96', - created: DateTime(2021, 1, 15), - name: 'Kreuzheben', - description: ''' + id: 9, + uuid: '521a5e4f-6f35-43e5-9d1c-6e75c4956e96', + created: DateTime(2021, 1, 15), + name: 'Kreuzheben', + description: '''

    Stelle dich mit etwas mehr als schulterbreitem Stand vor der Stange, die Füße zeigen leicht nach außen, die Stange ist direkt darüber und sehr nahe am Schienbein. Beuge die Knie (zeigen ebenfalls etwas nach außen) und neige den Oberkörper (bleibt während der ganzen Übung gerade). Greife die Stange schulterbreit mit einem Unter- und einem Obergriff.

    Ziehe nun die Stange nach oben. An der höchsten Stelle mache ein leichtes Hohlkreuz und drücke die Schultern nach hinten. Gehe wieder runter, wobei du darauf achtest, dass der Rücken gerade bleibt und sich nicht krümmt. Du kannst unten angekommen eine kleine Pause einlegen oder sofort weitermachen.

    ''', - exerciseId: 184, - language: tLanguage1, -); + exerciseId: 184, + languageId: tLanguage1.id, + languageObj: tLanguage1); final deadLiftPT = Translation( - id: 1401, - uuid: 'e570cd82-5a8f-4768-a2f3-8d60bad5c6e8', - created: DateTime(2021, 1, 15), - name: 'Levantamento terra', - description: ''' + id: 1401, + uuid: 'e570cd82-5a8f-4768-a2f3-8d60bad5c6e8', + created: DateTime(2021, 1, 15), + name: 'Levantamento terra', + description: ''' Fique firme, com os pés ligeiramente mais afastados do que os ombros. Fique diretamente atrás da barra, onde ela mal deve tocar sua canela, com os pés apontando um pouco para fora. Curve-se com as costas retas, os joelhos também apontando um pouco para fora. Agarre a barra com uma pegada na largura dos ombros, uma pegada por baixo e uma pegada reversa. Puxe o peso para cima. No ponto mais alto, faça uma leve depressão para trás e puxe a barra para trás. Segure 1 ou 2 segundos nessa posição. Desça, certificando-se de que as costas não estão dobradas. Depois de descer, você pode voltar assim que os pesos tocarem o chão ou fazer uma pausa, dependendo do peso.''', - exerciseId: 184, - language: tLanguage7, -); + exerciseId: 184, + languageId: tLanguage7.id, + languageObj: tLanguage7); final deadLiftIT = Translation( - id: 1402, - uuid: '7c088d54-6732-4d5e-aae8-9be8d4a1f111', - created: DateTime(2021, 1, 15), - name: 'Stacco', - description: ''' + id: 1402, + uuid: '7c088d54-6732-4d5e-aae8-9be8d4a1f111', + created: DateTime(2021, 1, 15), + name: 'Stacco', + description: ''' StaccoStacco Stacco''', - exerciseId: 184, - language: tLanguage13, -); + exerciseId: 184, + languageId: tLanguage13.id, + languageObj: tLanguage13); final deadLiftTranslations = [deadLiftEN, deadLiftDE, deadLiftPT, deadLiftIT]; final crunchesPT = Translation( - id: 1381, - uuid: '332b844f-816c-486d-8ef4-f58517514061', - created: DateTime(2021, 1, 15), - name: 'Abdominal', - description: - '''
    1. Deite-se de barriga para cima no chão com os joelhos dobrados.
    2. Curve os ombros em direção a pélvis. As mãos podem ficar atrás ou do lado do pescoço ou cruzadas sobre o peito.
    3. Repita
    ''', - exerciseId: 167, - language: tLanguage7, -); + id: 1381, + uuid: '332b844f-816c-486d-8ef4-f58517514061', + created: DateTime(2021, 1, 15), + name: 'Abdominal', + description: + '''
    1. Deite-se de barriga para cima no chão com os joelhos dobrados.
    2. Curve os ombros em direção a pélvis. As mãos podem ficar atrás ou do lado do pescoço ou cruzadas sobre o peito.
    3. Repita
    ''', + exerciseId: 167, + languageId: tLanguage7.id, + languageObj: tLanguage7); final crunchesES = Translation( - id: 1382, - uuid: 'ca89f09f-e7d0-4490-bf43-b539fd86c6ee', - created: DateTime(2021, 1, 15), - name: 'Abdominales', - description: - '''
    1. Acuéstese boca arriba en el suelo con las rodillas dobladas.
    2. Flexione los hombros hacia la pelvis. Las manos pueden estar detrás o al costado del cuello o cruzadas sobre el pecho.
    3. Repita
    ''', - exerciseId: 167, - language: tLanguage4, -); + id: 1382, + uuid: 'ca89f09f-e7d0-4490-bf43-b539fd86c6ee', + created: DateTime(2021, 1, 15), + name: 'Abdominales', + description: + '''
    1. Acuéstese boca arriba en el suelo con las rodillas dobladas.
    2. Flexione los hombros hacia la pelvis. Las manos pueden estar detrás o al costado del cuello o cruzadas sobre el pecho.
    3. Repita
    ''', + exerciseId: 167, + languageId: tLanguage4.id, + languageObj: tLanguage4); final crunchesFR = Translation( - id: 1383, - uuid: '5973bc39-5589-436d-aa68-f0cb22b6f385', - created: DateTime(2021, 1, 15), - name: 'Abdominaux', - description: - '''
    1. Allongez-vous sur le sol, face contre terre, genoux pliés.
    2. Courbez les épaules vers le bassin. Les mains peuvent être derrière ou à côté du cou ou croisées sur la poitrine.
    3. Répétez
    ''', - exerciseId: 167, - language: tLanguage12, -); + id: 1383, + uuid: '5973bc39-5589-436d-aa68-f0cb22b6f385', + created: DateTime(2021, 1, 15), + name: 'Abdominaux', + description: + '''
    1. Allongez-vous sur le sol, face contre terre, genoux pliés.
    2. Courbez les épaules vers le bassin. Les mains peuvent être derrière ou à côté du cou ou croisées sur la poitrine.
    3. Répétez
    ''', + exerciseId: 167, + languageId: tLanguage12.id, + languageObj: tLanguage12); final crunchesIT = Translation( - id: 1384, - uuid: 'd09f38a4-2c88-46ef-a847-cb66289d250b', - created: DateTime(2021, 1, 15), - name: 'Addominali', - description: - '''
    1. Sdraiati a pancia in su sul pavimento con le ginocchia piegate.
    2. Solleva il busto verso il bacino, a 30° / 40° dal suolo. Le mani possono essere dietro o accanto al collo o incrociate sul petto.
    3. Ripeti
    ''', - exerciseId: 167, - language: tLanguage13, -); + id: 1384, + uuid: 'd09f38a4-2c88-46ef-a847-cb66289d250b', + created: DateTime(2021, 1, 15), + name: 'Addominali', + description: + '''
    1. Sdraiati a pancia in su sul pavimento con le ginocchia piegate.
    2. Solleva il busto verso il bacino, a 30° / 40° dal suolo. Le mani possono essere dietro o accanto al collo o incrociate sul petto.
    3. Ripeti
    ''', + exerciseId: 167, + languageId: tLanguage13.id, + languageObj: tLanguage13); final crunchesNL = Translation( - id: 1385, - uuid: '930864f4-6200-4a7f-a8b0-7bdb6d401ef5', - created: DateTime(2021, 1, 15), - name: 'Crunch', - description: - '''
    1. Ga op je rug liggen en buig je knieën.
    2. Draai je schouders richting je bekken. Houd je handen achter of naast je nek of kruislings over je borstkas.
    3. Herhaal
    ''', - exerciseId: 167, - language: tLanguage6, -); + id: 1385, + uuid: '930864f4-6200-4a7f-a8b0-7bdb6d401ef5', + created: DateTime(2021, 1, 15), + name: 'Crunch', + description: + '''
    1. Ga op je rug liggen en buig je knieën.
    2. Draai je schouders richting je bekken. Houd je handen achter of naast je nek of kruislings over je borstkas.
    3. Herhaal
    ''', + exerciseId: 167, + languageId: tLanguage6.id, + languageObj: tLanguage6); final crunchesID = Translation( - id: 1386, - uuid: '447d0191-1f05-4e9b-8a17-6fdb4434359e', - created: DateTime(2021, 1, 15), - name: 'Crunch', - description: - '''
    1. Tiarap di lantai dengan lutut bengkok.
    2. Ikatkan bahumu ke pinggulnya. Tangan bisa berada di belakang atau di samping leher atau menyeberang di atas dada.
    3. Ulangi
    ''', - exerciseId: 167, - language: tLanguage23, -); + id: 1386, + uuid: '447d0191-1f05-4e9b-8a17-6fdb4434359e', + created: DateTime(2021, 1, 15), + name: 'Crunch', + description: + '''
    1. Tiarap di lantai dengan lutut bengkok.
    2. Ikatkan bahumu ke pinggulnya. Tangan bisa berada di belakang atau di samping leher atau menyeberang di atas dada.
    3. Ulangi
    ''', + exerciseId: 167, + languageId: tLanguage23.id, + languageObj: tLanguage23); final crunchesDE = Translation( - id: 4, - uuid: '0e10ac9b-ed1d-42c9-b8cc-123c22ccc5d5', - created: DateTime(2021, 1, 15), - name: 'Crunches', - description: ''' + id: 4, + uuid: '0e10ac9b-ed1d-42c9-b8cc-123c22ccc5d5', + created: DateTime(2021, 1, 15), + name: 'Crunches', + description: '''

    Lege dich auf eine Matte mit angewinkelten Beinen. Die Füße werden irgendwie festgehalten (Partner, Lanhghantel, o.Ä.) und die Hände werden hinter dem Nacken verschränkt. Aus dieser Position führe den Oberkörper so weit nach oben, bis Kopf oder Ellenbogen die angewinkelten Beine berühren.

    Es ist wichtig, dass dieser Vorgang mit einer rollenden Bewegung durchgeführt wird: die Wirbelsäule sollte sich Wirbel für Wirbel von der Matte lösen. Ein Hohlkreuz ist stets zu vermeiden.

    ''', - exerciseId: 167, - language: tLanguage1, -); + exerciseId: 167, + languageId: tLanguage1.id, + languageObj: tLanguage1); final crunchesEN = Translation( - id: 91, - uuid: 'd325dd5c-6833-41c7-8eea-6b95c4871133', - created: DateTime(2021, 1, 15), - name: 'Crunches', - description: - '''

    Lay down on your back a soft surface, the feet are on the floor. Ask a partner or use some other help (barbell, etc.) to keep them fixed, your hands are behind your head. From this position move your upper body up till your head or elbows touch your knees. Do this movement by rolling up your back.

    ''', - exerciseId: 167, - language: tLanguage2, -); + id: 91, + uuid: 'd325dd5c-6833-41c7-8eea-6b95c4871133', + created: DateTime(2021, 1, 15), + name: 'Crunches', + description: + '''

    Lay down on your back a soft surface, the feet are on the floor. Ask a partner or use some other help (barbell, etc.) to keep them fixed, your hands are behind your head. From this position move your upper body up till your head or elbows touch your knees. Do this movement by rolling up your back.

    ''', + exerciseId: 167, + languageId: tLanguage2.id, + languageObj: tLanguage2); final crunchesCS = Translation( - id: 1387, - uuid: 'bba98d12-499b-462a-982b-4be3875ec91f', - created: DateTime(2021, 1, 15), - name: 'Sedolehy', - description: - '''
    1. Lehni si na zem hlavou nahoru s pokrčenými koleny.Zvedni záda tak, aby se tvá ramena co nejblíže přiblížily ke kolenům. Plosky nohou včetně prstů by měly zůstat na zemi. Ruce mohou být za hlavou nebo přeložené v kříž na hrudi.
    2. Opakuj
    ''', - exerciseId: 167, - language: tLanguage9, -); + id: 1387, + uuid: 'bba98d12-499b-462a-982b-4be3875ec91f', + created: DateTime(2021, 1, 15), + name: 'Sedolehy', + description: + '''
    1. Lehni si na zem hlavou nahoru s pokrčenými koleny.Zvedni záda tak, aby se tvá ramena co nejblíže přiblížily ke kolenům. Plosky nohou včetně prstů by měly zůstat na zemi. Ruce mohou být za hlavou nebo přeložené v kříž na hrudi.
    2. Opakuj
    ''', + exerciseId: 167, + languageId: tLanguage9.id, + languageObj: tLanguage9); final crunchesHR = Translation( - id: 1388, - uuid: '8a564835-465b-47b5-a636-a086e390b310', - created: DateTime(2021, 1, 15), - name: 'Trbušnjaci', - description: '''''', - exerciseId: 167, - language: tLanguage22, -); + id: 1388, + uuid: '8a564835-465b-47b5-a636-a086e390b310', + created: DateTime(2021, 1, 15), + name: 'Trbušnjaci', + description: '''''', + exerciseId: 167, + languageId: tLanguage22.id, + languageObj: tLanguage22); final crunchesTR = Translation( - id: 1389, - uuid: 'c53a1e4f-c067-440a-a872-d4f48322e520', - created: DateTime(2021, 1, 15), - name: 'Yarım mekik', - description: - '''
    1. Dizlerinizi bükerek yere sırtüstü yatın.
    2. Omuzları leğen kemiğine doğru bükün. Eller boynun arkasında veya yanında olabilir ya da göğsün üzerinden geçebilir.
    3. Tekrarlayın
    ''', - exerciseId: 167, - language: tLanguage16, -); + id: 1389, + uuid: 'c53a1e4f-c067-440a-a872-d4f48322e520', + created: DateTime(2021, 1, 15), + name: 'Yarım mekik', + description: + '''
    1. Dizlerinizi bükerek yere sırtüstü yatın.
    2. Omuzları leğen kemiğine doğru bükün. Eller boynun arkasında veya yanında olabilir ya da göğsün üzerinden geçebilir.
    3. Tekrarlayın
    ''', + exerciseId: 167, + languageId: tLanguage16.id, + languageObj: tLanguage16); final crunchesEL = Translation( id: 1390, @@ -379,50 +381,51 @@ final crunchesEL = Translation( description: '''
    1. Ξαπλώστε ανάσκελα στο πάτωμα με τα γόνατα λυγισμένα.
    2. Κυρτώστε τους ώμους προς τη λεκάνη. Τα χέρια μπορεί να είναι πίσω ή δίπλα από τον αυχένα ή σταυρωμένα πάνω από το στήθος.
    3. Επαναλάβετε
    ''', exerciseId: 167, - language: tLanguage8, + languageObj: tLanguage8, + languageId: tLanguage8.id, ); final crunchesRU = Translation( - id: 1391, - uuid: 'f9d9d264-dcb9-4f6f-96d6-8df325dabdfe', - created: DateTime(2021, 1, 15), - name: 'Скручивания', - description: '''''', - exerciseId: 167, - language: tLanguage5, -); + id: 1391, + uuid: 'f9d9d264-dcb9-4f6f-96d6-8df325dabdfe', + created: DateTime(2021, 1, 15), + name: 'Скручивания', + description: '''''', + exerciseId: 167, + languageId: tLanguage5.id, + languageObj: tLanguage5); final crunchesHE = Translation( - id: 1392, - uuid: '1e79bbb1-e310-42d0-8e25-043fbf12043a', - created: DateTime(2021, 1, 15), - name: 'כפיפות בטן', - description: '''''', - exerciseId: 167, - language: tLanguage21, -); + id: 1392, + uuid: '1e79bbb1-e310-42d0-8e25-043fbf12043a', + created: DateTime(2021, 1, 15), + name: 'כפיפות בטן', + description: '''''', + exerciseId: 167, + languageId: tLanguage21.id, + languageObj: tLanguage21); final crunchesAR = Translation( - id: 1393, - uuid: '25129a40-e28f-418e-ba90-c0259b7b91d7', - created: DateTime(2021, 1, 15), - name: 'الطحن', - description: - '''
    1. الاستلقاء على الأرض مع ثني الركبتين.
    2. لف الكتفين نحو الحوض. يمكن أن تكون اليدين خلف العنق أو بجانبه أو متقاطعتين فوق الصدر.
    3. كرر التمرين
    ''', - exerciseId: 167, - language: tLanguage17, -); + id: 1393, + uuid: '25129a40-e28f-418e-ba90-c0259b7b91d7', + created: DateTime(2021, 1, 15), + name: 'الطحن', + description: + '''
    1. الاستلقاء على الأرض مع ثني الركبتين.
    2. لف الكتفين نحو الحوض. يمكن أن تكون اليدين خلف العنق أو بجانبه أو متقاطعتين فوق الصدر.
    3. كرر التمرين
    ''', + exerciseId: 167, + languageId: tLanguage17.id, + languageObj: tLanguage17); final crunchesZH = Translation( - id: 1394, - uuid: '45db81d5-df0f-4be1-9e3c-08d2291cfd88', - created: DateTime(2021, 1, 15), - name: '仰卧起坐', - description: - '''

    起始姿势:膝盖弯曲,脸朝上躺在地板上。

    步骤:

    1. 朝骨盆方向弯曲肩膀。 双手可以放在脖子后面或脖子旁边,也可以交叉在胸前。2.回到初始姿势。
    2. 重复。
    ''', - exerciseId: 167, - language: tLanguage24, -); + id: 1394, + uuid: '45db81d5-df0f-4be1-9e3c-08d2291cfd88', + created: DateTime(2021, 1, 15), + name: '仰卧起坐', + description: + '''

    起始姿势:膝盖弯曲,脸朝上躺在地板上。

    步骤:

    1. 朝骨盆方向弯曲肩膀。 双手可以放在脖子后面或脖子旁边,也可以交叉在胸前。2.回到初始姿势。
    2. 重复。
    ''', + exerciseId: 167, + languageId: tLanguage24.id, + languageObj: tLanguage24); final crunchesTranslations = [ crunchesPT, @@ -444,51 +447,51 @@ final crunchesTranslations = [ ]; final curlsEN = Translation( - id: 81, - uuid: '48a59aa8-4568-409c-8afe-f8cb99c558ea', - created: DateTime(2021, 1, 15), - name: 'Biceps Curls With Dumbbell', - description: ''' + id: 81, + uuid: '48a59aa8-4568-409c-8afe-f8cb99c558ea', + created: DateTime(2021, 1, 15), + name: 'Biceps Curls With Dumbbell', + description: '''

    Hold two barbells, the arms are streched, the hands are on your side, the palms face inwards. Bend the arms and bring the weight with a fast movement up. At the same time, rotate your arms by 90 degrees at the very beginning of the movement. At the highest point, rotate a little the weights further outwards. Without a pause, bring them down, slowly.

    Don't allow your body to swing during the exercise, all work is done by the biceps, which are the only mucles that should move (pay attention to the elbows).

    ''', - exerciseId: 92, - language: tLanguage2, -); + exerciseId: 92, + languageId: tLanguage2.id, + languageObj: tLanguage2); final curlsDE = Translation( - id: 26, - uuid: '8cbbffcc-1989-43de-9200-03869480398c', - created: DateTime(2021, 1, 15), - name: 'Bizeps KH-Curls', - description: ''' + id: 26, + uuid: '8cbbffcc-1989-43de-9200-03869480398c', + created: DateTime(2021, 1, 15), + name: 'Bizeps KH-Curls', + description: '''

    Halte zwei Kurzhantel mit ausgestreckten Armen neben dem Körper, die Handflächen zeigen nach innen. Beuge die Arme und brige die Hanteln mit einer schnellen Bewegung nach oben wobei sie gleichzeitig um 90 Grad gedreht werden. Am höchsten Punkt kann man die Hanteln ganz leicht weiter nach außen drehen. Ohne Pause wird das Gewicht nun kontrolliert nach unten gebracht. Beachte, dass die Bewegung nach oben schneller ist als nach unten.

    Während des Bewegungablaufs darf der Körper nicht mitschwingen. Die Ellenbogen bleiben dabei immer an der Stelle.

    ''', - exerciseId: 92, - language: tLanguage1, -); + exerciseId: 92, + languageId: tLanguage1.id, + languageObj: tLanguage1); final curlsES = Translation( - id: 1213, - uuid: 'a3ed40fb-83d3-4901-889f-6bba313e8c80', - created: DateTime(2021, 1, 15), - name: 'Curl de bíceps con mancuerna', - description: - '''Sujeta dos pesas, los brazos estirados, las manos a los lados, las palmas hacia dentro. Flexiona los brazos y sube el peso con un movimiento rápido. Al mismo tiempo, gira los brazos 90 grados al principio del movimiento. En el punto más alto, gira un poco las pesas hacia fuera. Sin pausa, bájalas lentamente.No permitas que tu cuerpo se balancee durante el ejercicio, todo el trabajo lo realizan los bíceps, que son los únicos músculos que deben moverse (presta atención a los codos).''', - exerciseId: 92, - language: tLanguage4, -); + id: 1213, + uuid: 'a3ed40fb-83d3-4901-889f-6bba313e8c80', + created: DateTime(2021, 1, 15), + name: 'Curl de bíceps con mancuerna', + description: + '''Sujeta dos pesas, los brazos estirados, las manos a los lados, las palmas hacia dentro. Flexiona los brazos y sube el peso con un movimiento rápido. Al mismo tiempo, gira los brazos 90 grados al principio del movimiento. En el punto más alto, gira un poco las pesas hacia fuera. Sin pausa, bájalas lentamente.No permitas que tu cuerpo se balancee durante el ejercicio, todo el trabajo lo realizan los bíceps, que son los únicos músculos que deben moverse (presta atención a los codos).''', + exerciseId: 92, + languageId: tLanguage4.id, + languageObj: tLanguage4); final curlsTranslations = [curlsEN, curlsDE, curlsES]; final raisesIT = Translation( - id: 1426, - uuid: '28bf0f7b-ceba-47a6-8807-3cbd3312c82f', - created: DateTime(2021, 1, 15), - name: 'Alzate Laterali', - description: '''Alzate LateraliAlzate Laterali''', - exerciseId: 348, - language: tLanguage13, -); + id: 1426, + uuid: '28bf0f7b-ceba-47a6-8807-3cbd3312c82f', + created: DateTime(2021, 1, 15), + name: 'Alzate Laterali', + description: '''Alzate LateraliAlzate Laterali''', + exerciseId: 348, + languageId: tLanguage13.id, + languageObj: tLanguage13); final raisesEN = Translation( id: 148, @@ -498,15 +501,16 @@ final raisesEN = Translation( description: '''This exercise works the deltoid muscle of the shoulder. The movement starts with the arms straight, and the hands holding weights at the sides or in front of the body. Body is in a slight forward-leaning position with hips and knees bent a little. Arms are kept straight or slightly bent, and raised through an arc of movement in the coronal plane that terminates when the hands are at approximately shoulder height. Weights are lowered to the starting position, completing one rep. When using a cable machine the individual stands with the coronal plane in line with the pulley, which is at or near the ground.[9] The exercise can be completed one shoulder at a time (with the other hand used to stabilize the body against the weight moved), or with both hands simultaneously if two parallel pulleys are available.''', exerciseId: 348, - language: tLanguage2, + languageId: tLanguage2.id, + languageObj: tLanguage2, ); final raisesDE = Translation( - id: 20, - uuid: '72e78f4d-65f7-4ddd-9247-cdc1e133fa80', - created: DateTime(2021, 1, 15), - name: 'Seitheben KH', - description: ''' + id: 20, + uuid: '72e78f4d-65f7-4ddd-9247-cdc1e133fa80', + created: DateTime(2021, 1, 15), + name: 'Seitheben KH', + description: '''
    1. Aufrechter Stand, Kopf nach vorne gerichtet, eine Kurzhantel in jeder Hand.
    2. Handflächen nach innen, in Richtung des Körpers, gerichtet.
    3. @@ -515,8 +519,8 @@ final raisesDE = Translation(
    4. Am höchsten Punkt hältst du für 1-2 Sekunden inne und ziehst deine Schulterblätter zusammen.
    5. Führe die Hanteln langsam wieder nach unten in die Ausgangsposition und atme ein.
    ''', - exerciseId: 348, - language: tLanguage1, -); + exerciseId: 348, + languageId: tLanguage1.id, + languageObj: tLanguage1); final raisesTranslations = [raisesIT, raisesEN, raisesDE]; diff --git a/test_data/workouts.dart b/test_data/workouts.dart index 2491c50d8..3c8984ef9 100644 --- a/test_data/workouts.dart +++ b/test_data/workouts.dart @@ -30,7 +30,8 @@ import './exercises.dart'; const weightUnit1 = WeightUnit(id: 1, name: 'kg'); const weightUnit2 = WeightUnit(id: 2, name: 'metric tonnes'); -const RepetitionUnit repetitionUnit1 = RepetitionUnit(id: 1, name: 'Repetitions'); +const RepetitionUnit repetitionUnit1 = + RepetitionUnit(id: 1, name: 'Repetitions'); const RepetitionUnit repetitionUnit2 = RepetitionUnit(id: 2, name: 'Hours'); WorkoutPlan getWorkout({List? exercises}) { diff --git a/test_driver/screenshot_driver.dart b/test_driver/screenshot_driver.dart index f98d10c7f..a4a4a44f2 100644 --- a/test_driver/screenshot_driver.dart +++ b/test_driver/screenshot_driver.dart @@ -1,18 +1,22 @@ import 'dart:io'; +import 'package:flutter/foundation.dart'; import 'package:integration_test/integration_test_driver_extended.dart'; // cf. https://dev.to/mjablecnik/take-screenshot-during-flutter-integration-tests-435k Future main() async { try { await integrationDriver( - onScreenshot: (String screenshotName, List screenshotBytes, [_]) async { + onScreenshot: (String screenshotName, List screenshotBytes, + [_]) async { final File image = await File(screenshotName).create(recursive: true); image.writeAsBytesSync(screenshotBytes); return true; }, ); } catch (e) { - print('An error occurred: $e'); + if (kDebugMode) { + print('An error occurred: $e'); + } } } From 73e30410501a146639e838f181a9951029fb673f Mon Sep 17 00:00:00 2001 From: oussama berhili Date: Wed, 8 Jan 2025 09:31:54 +0100 Subject: [PATCH 2/2] Update analysis options to use Flutter lints and adjust analyzer settings --- analysis_options.yaml | 200 +++++++++++++++++++++++++++++++++++------- 1 file changed, 167 insertions(+), 33 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 47cf66e55..2aae7b30b 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,38 +1,172 @@ -include: package:lint/analysis_options.yaml +include: package:flutter_lints/flutter.yaml analyzer: + strong-mode: + implicit-casts: true # to be changed + implicit-dynamic: true # to be changed errors: - missing_return: error - must_be_immutable: error - must_call_super: error - invalid_use_of_protected_member: error - parameter_assignments: error - sort_unnamed_constructors_first: error - sort_pub_dependencies: ignore - always_use_package_imports: error - invalid_annotation_target: ignore - type_annotate_public_apis: false - use_build_context_synchronously: warning + # Treat missing required parameters as a warning (not a hint) + missing_required_param: warning + # Treat missing returns as a warning (not a hint) + missing_return: warning + # Allow having TODOs in the code + todo: ignore + # Allow self-reference to deprecated members (we do this because otherwise we have + # to annotate every member in every test, assert, etc, when we deprecate something) + deprecated_member_use_from_same_package: ignore + # Ignore analyzer hints for updating pubspecs when using Future or + # Stream and not importing dart:async + # Please see https://github.com/flutter/flutter/pull/24528 for details. + sdk_version_async_exported_from_core: ignore - exclude: - - "**/*.g.dart" - - "**/generated/*" # Add the file to ignore here -fix: - data: - - always_put_required_named_parameters_first - - avoid_redundant_argument_values - - prefer_const_constructors - - use_key_in_widget_constructors +linter: + rules: + # These rules are documented on and in the same order as + # the Dart Lint rules page to make maintenance easier + # https://github.com/dart-lang/linter/blob/master/example/all.yaml + always_declare_return_types: true + always_put_control_body_on_new_line: true + always_require_non_null_named_parameters: true + always_specify_types: false # decided against using it for now + annotate_overrides: true + avoid_bool_literals_in_conditional_expressions: true + avoid_classes_with_only_static_members: true + avoid_dynamic_calls: false # to be changed + avoid_empty_else: 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_init_to_null: true + avoid_null_checks_in_equality_operators: true + avoid_relative_lib_imports: true + avoid_renaming_method_parameters: true + avoid_return_types_on_setters: true + avoid_returning_null_for_void: true + avoid_shadowing_type_parameters: true + avoid_single_cascade_in_expression_statements: true + avoid_slow_async_io: true + avoid_type_to_string: true + avoid_types_as_parameter_names: true + avoid_unnecessary_containers: true + avoid_unused_constructor_parameters: true + avoid_void_async: false + await_only_futures: true + camel_case_extensions: true + camel_case_types: false + cancel_subscriptions: true + cast_nullable_to_non_nullable: false # to be changed + constant_identifier_names: false + control_flow_in_finally: true + deprecated_consistency: true + directives_ordering: true + empty_catches: false + empty_constructor_bodies: true + empty_statements: true + exhaustive_cases: true + file_names: true + flutter_style_todos: false + hash_and_equals: true + implementation_imports: true + iterable_contains_unrelated_type: true + leading_newlines_in_multiline_strings: true + library_names: true + library_prefixes: true + library_private_types_in_public_api: false + list_remove_unrelated_type: true + missing_whitespace_between_adjacent_strings: false + no_adjacent_strings_in_list: true + no_duplicate_case_values: true + no_logic_in_create_state: true + non_constant_identifier_names: true + noop_primitive_operations: true + null_check_on_nullable_type_parameter: true + null_closures: true + overridden_fields: true + package_api_docs: true + package_names: true + package_prefixed_library_names: true + prefer_adjacent_string_concatenation: true + prefer_asserts_in_initializer_lists: true + prefer_collection_literals: true + prefer_conditional_assignment: true + prefer_const_constructors: true + prefer_const_constructors_in_immutables: true + prefer_const_declarations: true + prefer_const_literals_to_create_immutables: true + prefer_contains: true + prefer_equal_for_default_values: true + prefer_final_fields: true + prefer_final_in_for_each: true + prefer_final_locals: true + prefer_for_elements_to_map_fromIterable: true + prefer_foreach: 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_null_aware_operators: true + prefer_single_quotes: true + prefer_spread_collections: true + prefer_typing_uninitialized_variables: true + prefer_void_to_null: true + provide_deprecation_message: true + recursive_getters: true + sized_box_for_whitespace: true + slash_for_doc_comments: true + sort_constructors_first: false # good for code readability but later + sort_unnamed_constructors_first: true + test_types_in_equals: true + throw_in_finally: true + tighten_type_of_initializing_formals: true + type_init_formals: true + unnecessary_await_in_return: true + unnecessary_brace_in_string_interps: true + unnecessary_const: true + unnecessary_getters_setters: 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_statements: true + unnecessary_string_escapes: true + unnecessary_string_interpolations: true + unnecessary_this: true + unrelated_type_equality_checks: true + use_full_hex_values_for_flutter_colors: true + use_function_type_syntax_for_parameters: true + use_is_even_rather_than_modulo: true + use_key_in_widget_constructors: false + use_late_for_private_fields_and_variables: true + use_named_constants: true + use_raw_strings: true + use_rethrow_when_possible: true + use_test_throws_matchers: true + valid_regexps: true + void_checks: false +dart_code_metrics: + extends: + - recommended + rules: + - avoid-shadowing: false # we shadow a lot, e.g. context in callbacks + - avoid-unsafe-collection-methods: false # we use foo[index] where index may not exist in theory, but in practice they will, in tests. also we can just handle the exceptions when they occur + - prefer-prefixed-global-constants: false # we don't really care for the 'k' prefix + - prefer-single-widget-per-file: false + - avoid-passing-self-as-argument: false # fairly harmless. and e.g. drift calls are like this + - avoid-passing-async-when-sync-expected: false # we really like to do this in onTap() etc, and it seems harmless + - prefer-match-file-name: false # dieter wants to enable this. but requires a lot of renames. what does roland think? -dart: - code-actions-on-save: - source: - fix-all: true - organize-imports: true - fix-on-save: - - implicit-casts: false - fix: - sort-members: true - use-rational-asserts: true - # plugins: - # - custom_lint + formatter: + indent: 0 + line-length: 100 + cascading-widget-extensions: false \ No newline at end of file